我正在用角5制作一个简单的平均堆栈应用程序,我知道我的代码没有那么好的性能,也不使用最佳实践。此代码是产品列表的类型记录文件。我只想让我的产品显示集合产品中的“用户”字段与loggedinUser相等的位置。
目前,它正在显示我的所有产品,无论哪个用户登录。我不和模特或者猫鼬一起工作。
for循环不工作。据说'this.products‘是空的。有人能解释一下为什么它是空的,我怎么能解决这个问题呢?
import { Component, OnInit } from '@angular/core';
// Import the DataService
import { DataService } from '../../data.service';
import { UserService } from '../../user.service';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {
products: Array<any>;
productsCU : Array<any>;
ngOnInit() {
}
constructor(private _dataService: DataService , private userService: UserService) {
this._dataService.getInventory()
.subscribe(res => this.products = res);
for(var i = 0;i < this.products.length;i++){
if(this.products[i].user== userService.getNameUserLoggedIn()){
this.productsCU.push(this.products[i]);
}
}
}发布于 2017-12-06 15:04:00
尝试这样做,如果console.log有数据问题,那么它与ur services getInventoy()函数有关,以及从哪里获取数据。
this._dataService.getInventory().subscribe((res) => {
this.products = res;
console.log(this.products);
for()...
});我不重复你在这里做的方法,得到所有的产品,然后通过ID过滤。正如你已经提到的,它不是“性能”。您应该在后端专门查询这个问题,以获得用户id为"123“的产品。
话虽如此,在这里,array.filter似乎是合适的用例,而不是冗长的for循环。
let userProducts = this.products.filter(p => p.user == userService.getNameUserLoggedIn())其中"p“是this.products数组中的每个产品
https://stackoverflow.com/questions/47677316
复制相似问题