订阅角度2后数组为空

时间:2018-03-08 09:21:46

标签: arrays angular asynchronous

我想从数组中的api调用中获取数据,但这不会起作用:

export class DisplayProductComponent implements OnInit {

  @Input() CheckBox: string;

  constructor(private serverService: ServerService, private route: ActivatedRoute) {
  }

  products: any = [];
  id: any;
  test: any =[];
  private sub: any;

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
        this.id = params['slug'];
    });
    this.getCategoryByID(this.id);
    const productsToDisplay = this.products.forEach(element => {
        console.log(element)
    })
  }
  getCategoryByID(slug) {
    this.serverService.getProductByCategory(slug)
      .subscribe(
        (response) => response.map(product => {this.products.push(product)}),
        (error) => console.log(error)
      );  
  }
};

我对forEach有问题,因为我说这个。产品是空的

2 个答案:

答案 0 :(得分:0)

您在

结果之前正在执行forEach
this.serverService.getProductByCategory(slug)
        .subscribe(
            (response) => response.map(product => {this.products.push(product)}),
            (error) => console.log(error)
        ); 

所以你应该把foreach放在subscribe的结果中:

     this.serverService.getProductByCategory(slug)
        .subscribe(
            (response) => {response.map(product => {this.products.push(product)})
  const productsToDisplay = this.products.forEach(element => {
        console.log(element)
    })},
            (error) => console.log(error)
        );  

请记住.subscribe()是异步的,因此即使在另一条指令之前调用它,它的结果也可以稍后执行

答案 1 :(得分:0)

问题是您在服务工作完成之前记录产品(asynchrounous)

你可以尝试这个解决方案:

folder

的问候,