简体   繁体   English

angular rxjs 仅在第一个 observable 为 null 时订阅第二个 observable

[英]angular rxjs subscribe to second observable onlly if first observable is null

I have two methods that return observables.我有两种返回 observable 的方法。 If first returns some data then no need to call the second method.如果首先返回一些数据,则无需调用第二个方法。 But if the first method returns null then only call the second method.但是如果第一个方法返回 null 则只调用第二个方法。

getdefaultAddress(id) : Observable<Address[]> { 
    return this.http.get<Address[]>(this.url + 'users/' + id + '/addresses' + '?filter[where][default]=true')
  }

getFirstAddress(id): Observable<any>{
    return this.http.get<any>(this.url + 'users/' + id +'/addresses?filter[limit]=1'  )
  }

I can easily do this after subscribing to the first observable using if-else.在使用 if-else 订阅第一个 observable 后,我可以轻松地做到这一点。 Like喜欢

this.getdefaultAddress(id).subscibe(data =>{
    if(data) {
      // do something
    }

    else {
      this.getFirstAddress(id).subscibe(data =>{
        // do something
      })
    }
  })

Now how can I check this without really subscribing to first observable?现在如何在不真正订阅第一个 observable 的情况下检查这个? Any rxjs operator?任何 rxjs 运算符?

Thank you in advance先感谢您

const source1$: Observable<T| null>;
const source2$: Observable<T>;

const finalSource$ = source1$.pipe(
  switchMap(value => value ? of(value) : source2$) 
)

You return the outer source as long as it has an value.只要外部源具有值,就返回外部源。 The moment/event it gets undefined/null you switch to the source2$.当您切换到 source2$ 时,它变得未定义/为空的时刻/事件。

It's better to use for example concatMap :最好使用例如concatMap

import { EMPTY } from 'rxjs';
import { concatMap } from 'rxjs/operators';

this.getdefaultAddress(id)
  .pipe(
    concatMap(data => data === null ? EMPTY : this.getFirstAddress(id)),
  )
  .subscribe();

I belive you can use a switchMap operator, I cant test at the moment.我相信您可以使用 switchMap 运算符,我目前无法测试。

You're basically switching to a new inner observable when the source emits.当源发出时,您基本上切换到一个新的内部可观察对象。

this.getdefaultAddress(id).pipe(
  switchMap(data => {
    if (!data) {
      return this.getFirstAddress(id);
    }
  })
);

If you mean you want to get data from some store, and, if it is not there, get it from an API, here is what you should do:如果您的意思是要从某个商店获取数据,并且如果它不存在,则从 API 获取它,您应该执行以下操作:

import { of } from 'rxjs';
import { switchMap } from 'rxjs/operators';

this.getDataFromStorage().pipe(
  switchMap(data => data && data.length ? of(data) : this.requestDataFromAPI())
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM