【发布时间】:2021-10-06 14:40:25
【问题描述】:
我只想在 api 中进行调用并在可观察对象中重用数据,就像 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$))
)
}
这就是我想做的,访问已经拥有所有投资组合的 observable,然后从投资组合“Agora”中创建一个 observable
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)
})
}
我知道如果我这样做的话,find 的工作原理。
// 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)))
)
}
【问题讨论】:
标签: angular typescript rxjs