【问题标题】:complicated pipe chain with the HttpClient in Angular with RxJS使用 RxJS 在 Angular 中使用 HttpClient 的复杂管道链
【发布时间】:2020-09-26 13:36:02
【问题描述】:

我在 RxJS 方面没有太多经验,我想在我的 Angular 服务中使用 RxJS 管道做以下事情。

我尝试过使用 iif 函数,但我没有足够的经验。

Angular 版本是:Angular 9
RxJS 版本:6.5.5

通过 HttpClient 检查来自 GET 请求的响应是否为真
.... true -> 检查是否可以通过 HttpClient
访问网站 ............. 真 -> 设置 this.isOnline = true
.............................通过 HttpClient
从另一个 url 获取响应 ............................. 真 -> 设置 this.result = responseFromUrl
................................... 端管
............................. 假 -> throwError("无法获得结果")
................ false -> 设置 this.isOnline = false
................... 端管
.... false -> 结束管道

【问题讨论】:

  • true 和false 是指保证我们得到回复并根据回复的真实性继续处理,还是说true 对应于回复和@ 987654324@ 出错了?
  • 如果你发出一个 http 请求,你会得到一个成功响应或一个错误响应 -> 所以错误响应是假的,正常响应是真的

标签: javascript angular rxjs rxjs5 rxjs6


【解决方案1】:

试试下面的

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

http.get(api).pipe(
  concatMap(reponseOne => {
    return http.get(accessWebsiteApi).pipe(
      concatMap(responseTwo => {
        this.isOnline = true;
        return http.get(anotherUrl);
      }),
      catchError(errorTwo => {
        this.isOnline = false;
        return EMPTY;
      })
    );
  })
).subscribe(
  responseFromUrl => {
    this.result = responseFromUrl;
  },
  error => {
    console.error("cant get result");
  }
);

【讨论】:

  • 能否请您解释一下您的代码在做什么,我真的很想了解 rxjs
猜你喜欢
  • 2020-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-17
  • 1970-01-01
相关资源
最近更新 更多