角度切片对象数组

问题描述 投票:-1回答:1

我试图通过从角度为5的另一个对象数组中获取一个对象数组。我通过一个服务从我的API后端获取所有产品。我将结果传递给了array类型的属性产品。我想从我得到的结果中检索一个部分。好吧可能无法用文字描述,所以lemme删除代码。

export class HomeComponent implements OnInit {
discountedproducts: Products[];
latestproducts: Products[];
 cheapestdeals: Products[];
randomproducts: Products[];

constructor(private productservice: ProductService) {

}

ngOnInit() {
  this.productservice.getProductsBydiscount()
    .subscribe(res => this.discountedproducts = res);

    this.productservice.getProductsByNewest()
    .subscribe(res => this.latestproducts = res);

    this.productservice.getProductsByPrice()
    .subscribe(res => this.cheapestdeals = res);

    this.productservice.getProductsByRandom()
    .subscribe(res => this.randomproducts = res);
}

}

如果我做的事情

let slicedarray = latestproducts.slice(0, 3); 

在构造函数中,当我尝试使用ngFor循环显示它时,它不会输出任何内容。我怎么能做得更好?

javascript angular multidimensional-array angular5
1个回答
1
投票

你应该在回调.subscribe时这样做,否则你需要让latestproducts成为一个主题,然后订阅它。

this.productservice.getProductsByNewest()
    .subscribe(res => {
      this.latestproducts = res;
      this.slicedArray = res.slice();
    }
);

然后在slicedArray上做ngFor。

© www.soinside.com 2019 - 2024. All rights reserved.