【问题标题】:Convert Rxjs code to Angular 6 and latest rxjs将 Rxjs 代码转换为 Angular 6 和最新的 rxjs
【发布时间】:2018-09-13 09:37:45
【问题描述】:

场景:

  • Angular 新手
    正在尝试将 Angular 2 代码迁移到 Angular 6
  • 知道我是怎么做到的 可以用angular 6重写以下代码


使用 Angular 6 编写的代码:

return this._http.post(this.apiBaseUrl + "/api/login", body, options)
   .timeoutWith(Constant.timeout, Observable.throw(new Error(Constant.timeoutMsg)))
      .map(response => {
            const result = response.json() as LoginResultModel;

            if (result.AccessToken != null) {
                this.setLoginToken(result);
                return result;
            } else {
                return response;
            }
        });

【问题讨论】:

  • 请查看Update Angular 站点,看看您应该为迁移做哪些更改
  • @AbhishekKumar 请不要添加噪音,如对所有建议开放,请提出建议。谢谢你。这些编辑应该被拒绝并将被撤消。它们没有用。我们不会在 Stack Overflow 上提出这样的问题。

标签: angular rxjs angular6 rxjs6


【解决方案1】:

只需使用pipe 方法并将timeoutWithmap 运算符都作为函数作为其参数:

import { throwError } from 'rxjs';
import { map, timeoutWith } from 'rxjs/operators';

return this._httpClient.post<LoginResultModel>(this.apiBaseUrl + "/api/login", body, options)
  .pipe(
    timeoutWith(Constant.timeout, throwError(new Error(Constant.timeoutMsg))),
    map(result => {
      if (result.AccessToken != null) {
        this.setLoginToken(result);
        return result;
      } else {
        return response;
      }
    })
  );

更多关于 RxJS 6 中的 pipable 操作符:

https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md

注意我也使用了HttpClientModule,这里你不需要使用response.json() 方法,更多信息在这里:

https://angular.io/guide/http

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 2018-12-19
    • 2018-10-15
    • 2019-02-08
    • 2016-12-25
    • 2018-02-19
    相关资源
    最近更新 更多