this.route.paramMap.subscribe выполнить до моего ngOnInit в Angular - PullRequest
0 голосов
/ 12 октября 2019

У меня проблема с пониманием выполнения в фоновом режиме в Angular observables.

У меня есть служба с cateogoryChanged = new Subject<CategoryModel[]>();, а в моем компоненте 1 в ngOnInit У меня есть:

this.productsService.cateogoryChanged.subscribe((category) => {
      this.categoryList = category;
      console.log(this.categoryList.length)
      for (let i = 0; i < category.length; i++) {
        for (let j = 0; j < category[i].productModel.length; j++) {
          this.singleProducts.push(category[i].productModel[j]);
          this.singleProductsView.push(category[i].productModel[j]);

        }
      }
    })

и

 this.route.paramMap.subscribe(params => {
      console.log(this.categoryList.length + "paramMap")

      this.categoryName = params.get('category');
      this.id = parseInt(this.route.snapshot.paramMap.get('id'));
      console.log(this.categoryName);
      //this.categoryList = this.productsService.getList();
      if (this.categoryName != null) {
        console.log(this.categoryList);
        this.categoryList = [];
     //  this.singleProductsView = this.productsService.getListOfProduct(this.categoryName);


      }
      else {
        this.getAllProducts();


      }

    })

Как можно выполнить сначала route.paramMap, а после этого выполнить мой cateogoryChanged.subscribe

1 Ответ

2 голосов
/ 12 октября 2019

Вы можете использовать switchMap, это будет выглядеть примерно так:

this.route.paramMap.pipe(
    map(/* get categoryName from params here */),
    tap(categoryName => /* side effects here */),
    switchMap(() => this.productsService.cateogoryChanged),
).subscribe(/* process category list here */);
...