如何正确过滤 Observable/BehaviourSubject?

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

服务:

@Injectable({
  providedIn: 'root'
})
export class DeckService{
  private decks$ = new BehaviorSubject<Deck[]>([]);

  constructor(private http: HttpClient) {}

  public init(): void {
    this.http.get<Deck[]>('/api/decks').subscribe((decks : Deck[]) => {
      this.decks$.next(decks);
    });
  }

  public getDecks(): Observable<Deck[]> {
    return this.decks$.asObservable();
  }

  public getDeck(deck_id : number) : Observable<Deck> {
    return this.decks$.pipe(
      map(decks => decks.filter(deck => deck.deck_id === deck_id)[0])
    );
  }

}

成分:


  public decks$ : Observable<Deck[]>;
  public deckSelected$! : Observable<Deck | undefined>;

  constructor(private deckService : DeckService) {
    this.decks$ = this.deckService.getDecks();
    this.deckService.init();
  }
  
  ngOnInit() {
    this.deckSelected$ = this.deckService.getDecks().pipe(
      map((decks: Deck[]) => decks.find(deck => deck.deck_id === 58))
    );
  }


}

HTML:

<div *ngIf="deckSelected$ | async as deck">
  <h2>{{deck.deck_id}}</h2>
</div>

甲板型号:

export interface Deck {
  deck_id: number;
  name: string;
  description: string;
}

所以我想获取一个由id指定的卡片组。因此,我想首先获取可观察到的所有牌组,然后对其进行过滤。 因为使用两个端点太过分了,因为我已经将它们加载到应用程序中。

但是,当运行它时,它只会给我一个空白页面,没有任何渲染的项目。

angular rxjs angular2-observables
1个回答
0
投票

通常服务仅包含http客户端API调用,组件将包含代码的订阅部分,这是因为您可以控制可观察调用的执行顺序。

在下面的服务中,方法中没有订阅,而是用

tap
代替来执行副作用,例如设置
BehaviorSubject
的值。

@Injectable({
  providedIn: 'root'
})
export class DeckService{
  private decks$ = new BehaviorSubject<Deck[]>([]);

  constructor(private http: HttpClient) {}

  public init(): void {
    return this.http.get<Deck[]>('/api/decks').pipe(
      tap((decks : Deck[]) => {
        this.decks$.next(decks);
      })
    );
  }

  public getDecks(): Observable<Deck[]> {
    return this.decks$.asObservable();
  }

  public getDeck(deck_id : number) : Observable<Deck> {
    return this.decks$.pipe(
      map(decks => decks.filter(deck => deck.deck_id === deck_id)[0])
    );
  }
}

在控制器中,您可以嵌套 API 调用,以便逻辑按正确的顺序发生。

  public decks$ : Observable<Deck[]>;
  public deckSelected$! : Observable<Deck | undefined>;

  constructor(private deckService : DeckService) {
    this.decks$ = this.deckService.getDecks();
    this.deckSelected$ = this.deckService.init().pipe(
      tap((decks: Deck[]) => decks.find(deck => deck.deck_id === 58)),
    );
  }
  
  ngOnInit() {
    this.deckSelected$ = this.deckService.getDecks().pipe(
      map((decks: Deck[]) => decks.find(deck => deck.deck_id === 58))
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.