I have this code :
const id = 1; // id = 2
of([{id: 1, name: 'abc'}]).pipe(
map(items => items.find(item => item.id === id)),
switchMap(item => item ? of(item) : this.makeHttpRequest(id))
);
makeHttpRequest(id: number): Observable<IdNamePair>{}
in short,
if object with specific id is found in array, return observable of({id: 1, name: 'abc'})
if object not found in array, return observable returned by
this.makeHttpRequest(id) method
I want to eliminate the of(item) operator.
This code works but is there a way without creating a new observable and reusing the one created by "map()" ?
edit:
export class MyService {
private _list = new BehaviorSubject([{id: 1, name: 'abc'}]);
list = this._list.asObservable();
findOne(id: number) {
this.list.pipe(
map(items => items.find(item => item.id === id)),
switchMap(item => item ? of(item) : this.makeHttpRequest(id))
);
}
}
in Angular component :
export class MyComponent {
item$: Observable<IdNamePair>;
constructor(private service: MyService) {}
ngOnInit() {
this.item$ = this.service.findOne(1); // or (2), id comes from router
}
}
switchMapas parameter has to return an Observable. In the case ofitemnull, this is performed bythis.makeHttpRequest(id). In the other case you have to find a way to create an Observable, andofseems the most natural way. - Picciof()s so which one you want to get rid of? - martinof. For examplefromcoupled withfilter, but you would wait for completion, for example usingtoArray. The point is, the solution would be more complicated and not necessarily elegant. - madjaoue