首页 > 解决方案 > 与 BehaviorSubject 共享数据 api - 架构 Observables Store

问题描述

我只想在 api 中调用并重用 observable 中的数据,就像 redux 中的一种存储一样。

API 网址: http ://demo5095413.mockable.io/consolidado

Stackblitz 项目 https ://stackblitz.com/edit/angular-ivy-iy9zhv?file=src/app/core.service.ts

负责与 api 连接的服务

@Injectable({
  providedIn: 'root'
})
export class ConsolidadoApi {
  
  constructor(private http: HttpClient) { }

  getInvestiments(): Observable<any> {
    return this.http.get<PosicaoConsolidada>(`${environment.basePosicaoConsolidada}`)
      .pipe(
        map(res => res),
        shareReplay(),
      )
  }
}

处理数据的服务,我的门面层(store) 最初是这样,这个observable负责在api中进行调用。最后我发出一个 BehaviorSubject

export class CoreService {

    private subject = new BehaviorSubject<any>([]);
    investment$: Observable<any> = this.subject.asObservable();
    
    constructor(private api: ConsolidadoApi, private loadingService: LoadingService, public messagesService: MessagesService, public state: StateService) {
        this.getInvesmentsPortifolio$()
     }

    public getInvesmentsPortifolio$(): Observable<Carteiras> {
        return this.api.getInvestiments()
            .pipe(
                map(response => response.carteiras),
                catchError(err => {
                    const message = "Error Investments";
                    this.messagesService.showErrors(message);
                    console.log(message,err);
                    return throwError(err);
                }),
                tap(investment$ => this.subject.next(investment$))
            )
    }

这就是我想做的事情,访问已经拥有所有投资组合的可观察对象,并从那里从投资组合“Agora”创建一个可观察对象

getPortifolioAgora(): Observable<any> {
    return this.investment$
        .pipe(
            map(response => response.carteiras.find(
                carteira => carteira.tipoInvestimento === "AGORA"
            ))
        );
}

但在我的组件中不起作用

    constructor(public coreService: CoreService, private loadingService: LoadingService) { }

  ngOnInit(): void {
    this.loadData()
  }

  public loadData(){
    this.loadingService.loadingOn()
    
    this.coreService.getPortifolioAgora().subscribe(res => {
      console.log(res)
    })

    this.coreService.getInvesmentsPortifolio$().subscribe(res => {
      this.carteiras = res
      console.log('All portifolio investments----->',res)
    })

  }

在此处输入图像描述 属性未定义?

我知道如果我这样做,查找工作。

// In this observable I access directly in the api and I can access the investment portfolio Agora
// it's working, but I wouldn't want to do it that way because I would have made another call on the server
public portifolioAgora$(): Observable<Carteiras> {
    return this.api.getInvestiments()
        .pipe(
            map(response => response.carteiras.find(
                carteira => carteira.tipoInvestimento === "AGORA"
            )),
            finalize(() => this.loadingService.loadingOff())
            //tap(data => console.log(data, JSON.stringify(data)))
        )
}

在此处输入图像描述

标签: angulartypescriptrxjs

解决方案


由于getInvesmentsPortifolio$()您只将carteiras数组添加到BehaviourSubjectSo中,因此在getPortifolioAgora更新地图代码中

 getPortifolioAgora(): Observable<any> {
    return this.investment$.pipe(
      map((response) =>
        response.find((carteira) => carteira.tipoInvestimento === 'AGORA')
      )
    );
  }

问题也可能是您之前调用getPortifolioAgora过,在初始加载时getInvesmentsPortifolio$结果将不可用Subject


推荐阅读