【问题标题】:Execute a second http call only if first fails仅在第一次失败时执行第二次 http 调用
【发布时间】:2019-07-16 08:06:07
【问题描述】:

尝试通过管道传递两个 Angular http 调用,其中第二个调用只有在第一个失败时才会执行。

第一次调用是:

 return this.http.get<AssetGroupHistoryResponseModel>('./assets/data.json');

如果 data.json 不存在,则会引发 404 Not Found 错误,它应该调用适当的 API:

return this.http.get<AssetGroupHistoryResponseModel>(url);

不知道如何使用 rxjs 获得这种行为。

【问题讨论】:

    标签: angular http rxjs reactive-programming


    【解决方案1】:

    您可以使用 RXJS 中的 catchError 运算符来实现。

    来,试试看:

    import { Component } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { catchError } from 'rxjs/operators';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
    
      constructor(private http: HttpClient) {}
    
      ngOnInit() {
        this.getData()
          .subscribe(
            res => console.log(res)
          )
      }
    
      getData() {
        return this.http.get('http://jsonplaceholder.typicode.com/posts/1')
          .pipe(
            catchError(error => this.http.get('https://jsonplaceholder.typicode.com/users/1'))
          );
      }
    }
    

    PS:请注意,第一次 API 调用将导致错误,因为它使用 http,而应用程序将在 https 上运行。因此,您将获得user 数据而不是post 数据记录到控制台。


    这里有一个Working Sample StackBlitz 供您参考。

    【讨论】:

    • 非常感谢!这正是我需要的运算符!
    【解决方案2】:

    您可以查看 Angular 中的错误处理。使用 Angular 的 HttpClient 以及来自 RxJS 的 catchError,我们可以轻松地编写一个函数来处理每个服务中的错误。当第一个返回错误时,只需触发第二个 http cal。

    Example Here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-01
      • 1970-01-01
      • 2012-07-31
      • 2021-04-02
      • 2010-12-21
      • 2014-07-05
      • 2017-05-20
      • 1970-01-01
      相关资源
      最近更新 更多