ngrx 组件存储 select returns anonymousSubject 而不是 Observable

ngrx component store select returns anonymousSubject instead of Observable

我正在使用 ngrx 组件存储从后端获取搜索结果。但是,我无法获得状态的单个值,而是获得了一个匿名主题。这个 anonymousSubject 有需要的数据,但它在对象中嵌套得很深。

当我在 html 中迭代返回的可观察对象时,我可以获得正确的值,但现在我只需要一个特定的值 (state.result[0]),但我不能这样做.

有人可以阐明我如何从 anonymousSubject 访问单个值吗?提前致谢!

Component.store

export interface SearchResultState {
  result: Array<any>;
}

const defaultState: SearchResultState = {
  result: []
};

@Injectable()
export class SearchStore extends ComponentStore<SearchResultState> {
  constructor(
    private readonly _http: HttpClient,
    private readonly _notificationHandler: NotificationHandlerService
  ) {
    super(defaultState);
  }
  readonly loadSearchResult = this.effect((trigger$: Observable<{ query: string; apiLinks: Array<string> }>) =>
    trigger$.pipe(
      debounceTime(200),
      switchMap((action) => {
        if(!action.query.length) {
          return of(SearchActions.searchSuccess({result: {}}));
        }
        const headers: any = {
          'Content-Type': 'application/x-www-form-urlencoded',
          Accept: 'application/json',
        };
        const httpOptions: { headers: HttpHeaders } = {headers: new HttpHeaders(headers)};

        const apiCalls = [];
        for (const apiLink of action.apiLinks) {
          apiCalls.push(this._http.get(`${API_URL}${apiLink}${action.query}`,  httpOptions).pipe(
            map((resp: any) => resp),
          ));
        }

        return forkJoin(apiCalls).pipe(
          map((result) => {
            console.log(result); //prints the right result
            return this.setSearchResult({result});
          }),
          catchError(async error => {
            this._notificationHandler.showError();
            return SearchActions.searchFailed({error});
          })
        );
      })
    )
  );

  readonly setSearchResult = this.updater((state, result: any) => ({...state, result}));
  readonly searchResult$: Observable<Array<any>> = this.select(state => {
    console.log( 'state', state); //prints nothing unless used in the html
    return state.result;
  });

Component.ts(部分)

  public _searchResult$ = this.searchStore.searchResult$;

  public search($event: string): void {
    this.searchStore.loadSearchResult({query: $event, apiLinks: this.apiLinks});
    console.log(this._searchResult$); //prints the anonymousObject
    this.searchResults.emit(this._searchResult$);
  }

我得到一个 anonymousSubject 而不是商店的实际值的原因是我还没有订阅它。在 HTML 中,这是通过异步管道完成的。

为了让它工作,我添加了以下行:

  ngOnInit(): void {
    this.searchSub = this.searchStore.searchResult$.subscribe(state => {
      console.log(state.result); //prints the right values
    });
  }

  ngOnDestroy(): void {
    this.searchSub?.unsubscribe();
  }