RxJs:条件switchMap,如果发出的值为空

时间:2018-07-12 05:17:14

标签: angular rxjs

我有此代码:

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>{}

简而言之,

  • 如果在数组中找到具有特定ID的对象,则返回observable of({id:1,name:'abc'})

  • 如果在数组中找不到对象,则返回
    返回的observable this.makeHttpRequest(id)方法

我要消除of(item)运算符。

此代码有效,但是有没有办法创建新的可观察对象并重用“ map()”创建的对象?

编辑:

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))
                );
    }
}

在Angular组件中:

export class MyComponent {

    item$: Observable<IdNamePair>;

    constructor(private service: MyService) {}

    ngOnInit() {
            this.item$ = this.service.findOne(1); // or (2), id comes from router
    }
}

1 个答案:

答案 0 :(得分:0)

您可以

const id = 1; // id = 2

const [hasItem, noItem] = of([{id: 1, name: 'abc'}]).pipe(
            map(items => items.find(item => item.id === id)),
            partition(Boolean)
        );

const res = merge(hasItem, noItem.pipe(switchMapTo(this.makeHttpRequest(id))