代码之家  ›  专栏  ›  技术社区  ›  Wolf359

rxjs:如果发出的值为空,则条件switchmap

  •  1
  • Wolf359  · 技术社区  · 6 年前

    我有这个密码:

    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 的({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))
                    );
        }
    }
    

    在角度分量中:

    export class MyComponent {
    
        item$: Observable<IdNamePair>;
    
        constructor(private service: MyService) {}
    
        ngOnInit() {
                this.item$ = this.service.findOne(1); // or (2), id comes from router
        }
    }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   dsych    6 年前

    你可以

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