簡體   English   中英

Pipe 可觀察訂閱 map angular

[英]Pipe Observable subscription with map angular

其實我想用一個數組值作為參數調用另一個 function 。 我從一個主題中獲取數組:

this.shopService.$getShops().pipe(map(
  shops => {
    console.log(shops[0]);
  }
)).subscribe();

訂閱基於此:

      private newShopsSubj = new BehaviorSubject(undefined);

  setShops(shops: any) {
    this.newShopsSubj.next(shops);
  }


  $getShops(): Observable<any> {
    return this.newShopsSubj.asObservable();
  }

實際上代碼正在運行......但是console.log調用以undefined結束。 不知何故,我找不到合適的解決方案。

我想做這樣的事情:

   this.shopService.$getShops().subscribe(resp => {
this.shopService.getProductsByShopID(resp[0].id).subscribe(resp
=> {do something...};});

但它實際上失敗了,因為resp[0].id保持undefined ......我對 map 的嘗試失敗了。

任何幫助高度贊賞...

謝謝

胡喬

就像在其他答案中一樣...如果在設置值之前調用$getShops() ,您將得到undefined ,因為這是初始值。 您可以將其初始化為空數組,或者使用 rxjs filter器過濾掉undefined的值。 此外,我會將這些請求與例如switchMapmergeMap ,因為不建議嵌套訂閱。 所以我建議如下:

private newShopsSubj = new BehaviorSubject([]);
public newShopsSubj$ = this.newShopsSubj.asObservable();

和組件代碼:

import { mergeMap, filter } from 'rxjs/operators';
import { of } from 'rxjs';

// ...

this.shopService.newShopsSubj$.pipe(
  mergeMap((shops: any[]) => {
    // do a check that that there is an object
    if (shops && shops.length) {
      return this.shopService.getProductsByShopID(shops[0].id)
    }
    // no shops, so return...
    // empty array, since assuming the above function returns array of products
    return of([]);
  })
).subscribe((products: any[]) => {
  // check if products exist and do your magic!
})

或如前所述,將您的 BehaviorSubject 初始值設置為undefinedfilter掉這些值:

this.shopService.newShopsSubj$.pipe(
  filter(shops => !!shops)
  mergeMap((shops: any[]) => {
  // .....

請注意,我在這里使用過any 不要使用它。 將您的數據輸入到模型中。 (我更喜歡接口)。

並記得在OnDestroy中取消訂閱!

BehaviourSubject將當前值發送給新訂閱者。

在這里,您正在使用undefined的初始值對其進行初始化

private newShopsSubj = new BehaviorSubject(undefined);

所以當你訂閱它如下

  this.shopService.$getShops().subscribe(resp => {
this.shopService.getProductsByShopID(resp[0].id).subscribe(resp
=> {do something...};});

最初,它會得到resp的響應。 要解決此問題,您可以使用Subject而不是BehaviorSubject或使用適當的商店 object 初始化BehaviourSubject

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM