我combineLatest
用来将数据从一个对象websocket
合并database
到一个对象中。每次websocket
发送数据时,我的数据都会刷新。尽管我也想通过按下按钮手动刷新页面上的数据。不幸combineLatest
的是,没有检测到我HttpGet
请求获取最新数据。
export class ShowTestDataComponent implements OnInit {
stockData: RootObject;
private stocksData$: WebSocketSubject<MessageEvent>;
private stocksResources$: Observable<DbObject[]>;
constructor(private stockService: StockService, private webSocketService: WebSocketServiceService) {
this.stocksData$ = this.webSocketService.connect();
this.stocksResources$ = this.stockService.getStocksResources();
}
buyStock(code, quantityToBuy): void {
const dto: DbObject = {
code: code,
quantity: quantityToBuy
};
this.stockService.buyStock(dto).pipe(
mergeMap(() => this.stockService.getStocksResources())
).subscribe((res) => this.stocksResources$ = of(res));
}
prepareStockData(): void {
combineLatest(
this.stocksData$,
this.stocksResources$,
(stockData: RootObject, stockResources: DbObject[]) => ({
stockData,
stockResources
})
).subscribe((pair) => {
this.stockData = JSON.parse(pair.stockData.data);
this.stockData.Items.forEach(item => {
item.Quantity = pair.stockResources.find(d => d.code === item.Code).quantity;
});
});
}
ngOnInit() {
this.prepareStockData();
}
}
如您所见,如果我按下BUY
UI,则将buyStock
执行方法并执行this.stockService.buyStock(dto)
更改 DB 中的数据,然后this.stockService.getStocksResources()
刷新 DB 中的数据。一切正常,数据已更改但数据未刷新(comibneLatest 未检测到来自stocksResources$
这是我的服务,但我认为问题出在组件中。
export class StockService {
apiUrl = "http://localhost:5001/api/values";
constructor(private http: HttpClient) { }
getStocksResources(): Observable<DbObject[]> {
return this.http.get<DbObject[]>(this.apiUrl + "/stocks");
}
buyStock(data: DbObject){
return this.http.post<DbObject>(this.apiUrl + "/quantity", data);
}
}