繁体   English   中英

如何根据另一个 Observable 的结果调用一个 Observable 并返回一个 Observable

[英]How to call an Observable based on outcome of another Observable and return an Observable

Angular 10,创建一个返回 Observable 的服务方法(User 是我创建的自定义对象)。 我希望添加(一个 observable)服务方法,它会告诉我服务是否已启动并正在运行,如果没有,我想返回一个不同的 Observable,这个是从本地资源加载的。

伪代码:

if(serviceRunning()){
  return getUserFromService();
}else{
 return getUserFromLocalResource();
}

我的实际方法(这些都驻留在我的 UserService 模块中,并从我的控制器方法中调用):

serviceRunning() {
  // Calls service method serviceRunning which returns boolean.
  return this.http.get<boolean>(this.nodeUserSvcUrl + 'api/serviceRunning');
}

getUser(name: string): Observable<User> {
  if (this.serviceRunning()) { // Pseudo code...this line obviously does not work
    // Return user data from service
    return this.http.get<User>(this.nodeUserSvcUrl + 'api/users/' + name);
  } else {
    // Return data from local resource
    return this.getStaticUser(); 
  }
}

// Get local user data
getStaticUser() {
  return this.http.get<User>(this.usersUrl + 'users.json');
}

我尝试了无数的 mergeMap、forkJoin、concatMap 代码,但没有任何效果。 最接近的解决方案与此类似:( Angular4 如何将 forkJoin 与 flatMap 链接起来),但他没有返回 Observable - 我需要这样做 因此我觉得我不能像他的代码那样订阅 forkJoin/concatMap 结果。

任何帮助,将不胜感激!

更新:根据下面 Sivakumar 的回复,这是我的实际实现,对于那些可能需要它的人:

getUser() {
  return this.serviceRunning().pipe(
    switchMap(val => {
      var tmp: Observable<User>;
      val ? 
        tmp = this.http.get<User>(this.nodeUserSvcUrl + 'api/users/' + name)
      :
        tmp = this.getStaticUser();
      return tmp;
    })
  );
}

您可以在这种情况下使用switchMap

工作堆栈闪电战

import { Injectable } from "@angular/core";
import { of } from "rxjs";
import { switchMap } from "rxjs/operators";

@Injectable({
  providedIn: "root"
})
export class TestService {
  test: boolean = true;

  serviceRunning() {
    return of(this.test).pipe(
      switchMap(val =>
        val ? this.getUserFromRemote() : this.getUserFromLocal()
      )
    );
  }

  getUserFromRemote() {
    return of("User from Remote");
  }

  getUserFromLocal() {
    return of("User from Local");
  }
}

您可以从如下所示的另一种方法返回serviceRunning方法,并且您可以订阅 main 方法(getUsers()),这是您的要求

getUsers() {
  return this.serviceRunning();
}

暂无
暂无

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

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