首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用角5的列表操作

使用角5的列表操作
EN

Stack Overflow用户
提问于 2017-12-06 15:00:38
回答 1查看 1.7K关注 0票数 0

我正在用角5制作一个简单的平均堆栈应用程序,我知道我的代码没有那么好的性能,也不使用最佳实践。此代码是产品列表的类型记录文件。我只想让我的产品显示集合产品中的“用户”字段与loggedinUser相等的位置。

目前,它正在显示我的所有产品,无论哪个用户登录。我不和模特或者猫鼬一起工作。

for循环不工作。据说'this.products‘是空的。有人能解释一下为什么它是空的,我怎么能解决这个问题呢?

代码语言:javascript
复制
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]);
                    }
                }

  }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-06 15:04:00

尝试这样做,如果console.log有数据问题,那么它与ur services getInventoy()函数有关,以及从哪里获取数据。

代码语言:javascript
复制
this._dataService.getInventory().subscribe((res) => {
   this.products = res;
   console.log(this.products);

   for()...

});

我不重复你在这里做的方法,得到所有的产品,然后通过ID过滤。正如你已经提到的,它不是“性能”。您应该在后端专门查询这个问题,以获得用户id为"123“的产品。

话虽如此,在这里,array.filter似乎是合适的用例,而不是冗长的for循环。

Objects/Array/filter

代码语言:javascript
复制
let userProducts = this.products.filter(p => p.user == userService.getNameUserLoggedIn())

其中"p“是this.products数组中的每个产品

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47677316

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档