如果调用一个 api 失败调用另一个 api,如果两者都失败 return 一个错误

If call to one api fails call another api, if both fail return an error

我正在尝试在 Angular 中执行以下伪代码。对于 getData1(),我使用的是管道和地图,但是当对 getData2() 进行相同的调用时,它不允许我调用地图。我还需要能够对 getData() 进行单元测试,但是测试嵌套调用似乎很复杂

let data = '';

when called on init
  getData().subscribe(res=>{this.data = res.data})


getData():Observable{
  Make request to getData1()
    if getData1() success
      return response
    () => { // call this if getData1() fails
      if http get to third party api fails (e.g. its down)
        Make request to getData2()
          if getData2() success
            return response
    }
  If both fail
    send error to be handled by another service
}

getData1(): Observable<TestData1Res> {
 return http.get(external url 1);
}
getData2(): Observable<TestData2Res>  {
 return http.get(external url 2);
}

如何阻止主方法调用订阅中的响应出现错误“属性 'testData' 在类型 'TestData1Res| TestData2Res' 上不存在,其中只有 TestData2Res 包含 属性 'testData' 来自两个 api 的响应将具有不同的属性

例如 。订阅( (资源)=> { if (res.testData) { << 这个消息的错误 } }

sandbox link
可以简单的用catchError 和return 第二次调用第一次失败时在subscribe 中响应return,如果两次调用都失败会进入subscribe 的错误。

// a call that always passes
let fakeCall = (d = 10) => of(d);

// a call always fails
let fakeError = (e = 10) => throwError(new Error('fake error!: ' +  e));

// here it will make first call only and ignore second call
fakeCall(10).pipe(catchError(c => fakeCall(20)))
.subscribe((r) => console.log('response', r), 
e => console.log('error',e)); 
// repsponse 10

// here it will make first call but not second so second error has not impact
fakeCall(10).pipe(catchError(c => fakeError(20)))
 .subscribe(
   (r) => console.log('response', r), 
   e => console.log('error',e)); 
   // response 10

// here the it will make second call and return response of second call
   fakeError(10).pipe(catchError(c => fakeCall(20)))
.subscribe(
  (r) => console.log('response', r), 
  (e) => console.log('error',e)); 
  // response 20


fakeError(10).pipe(catchError(c => fakeError(20)))
.subscribe(
(r) => console.log('response', r), 
(e) => console.log('error',e)); 
// error 20