在我的Angular 4应用程序中,以下是一项服务,用于维护预订对象列表。该预订清单是一个主题。
//imports
@Injectable()
export class BookingTreeService {
selBooking: Booking;
bookingList: Array<Booking> = [];
bkgList$: Observable<Array<Booking>>;
private bkgListSubject: Subject<any>;
constructor( private resHttp: ResHttpService) {
this.bkgListSubject = new Subject<Array<Booking>[]>();
this.bkgList$ = this.bkgListSubject.asObservable();
}
loadBooking(bookingId:number): Observable<any> {
let item = this.bookingList.filter(b => b.bookingId === bookingId);
if (item && item.length > 0) {
return this.retrieveBooking(bookingId);
// here, I don't want to call http call. Need to update the booking tree
}
else {
return this.loadBookingAndLock(bookingId);
}
}
loadBookingAndLock(bookingId: any): Observable<any> {
return this.resHttp.loadBookingAndLock(bookingId)
.map(response => {
//handle response
})
.catch(this.handleError);
}
retrieveBooking(bookingId: any): Observable<any> {
return this.resHttp.retrieveBooking(bookingId)
.map(response => {
//handle response
})
.catch(this.handleError);
}
addBooking(booking: Booking) {
this.bookingList.push(booking);
this.updateBookingTree(booking);
}
updateBookingTree(booking: Booking):void {
this.bookingList.map((b:Booking) => {
b.active = b.bookingId === booking.bookingId;
});
this.bkgListSubject.next(this.bookingList);
}
}
在组件中,我在ngOnInit内部调用loadBooking,如下所示。
loadBooking() {
this.paramsSubscription = this.route.params
.switchMap((params: Params) => this.bkgTreeService.loadBooking(+params['id']))
.subscribe(
response => {
},
(error) => {
console.log(error);
}
);
}
如果所选预订已包含在预订树中,则不想再次调用http请求,而只想更新预订树。但是在switchMap内部,它仅接受Observable。这样怎么处理?
任何建议都值得赞赏。
答案 0 :(得分:0)
据我了解,您想缓存数据,因此您可以使用 shareReplay 使用Rxjs缓存。
更多详细信息,请访问:-https://blog.thoughtram.io/angular/2018/03/05/advanced-caching-with-rxjs.html
答案 1 :(得分:0)
拨打电话时,必须使用“轻按”存储预订清单
loadBookingAndLock(bookingId: any): Observable<any> {
return this.resHttp.loadBookingAndLock(bookingId)
//When the observable finished
.pipe(tap(response=>{
//we concat the response to the bookingList
if (!this.bookingList.find(b=>b.bookingId==bookingId)
this.bookingList.concat(response);
}))
.catch(this.handleError);
}