【问题标题】:Angular 5 / Typescript/RxJS - get data from ObservableAngular 5 / Typescript/RxJS - 从 Observable 获取数据
【发布时间】:2018-02-20 15:09:10
【问题描述】:

我有这个打字稿方法来登录用户:

onSubmit() {
    if (this.form.valid) {
      this.authService.login(this.form.value).map(res => this.loginResponse = res.json).subscribe(
        success => {
          console.log('Response: ' + this.loginResponse);
        },
        error => {
          this.loginFailed = true;
          setTimeout(()=>{   
            this.loginFailed  = false;
          }, 3000);
          console.error('ERROR login.component: ' + error);
        }
      );     
    }
    this.formSubmitAttempt = true;            
  }

实际上我不知道如何在此处获取响应数据 .map(res => this.loginResponse = res)

console.log 的输出是:

Response: function () {
    if (typeof this._body === 'string') {
        return JSON.parse(/** @type {?} */ (this._body));
    }
    if (this._body instanceof ArrayBuffer) {
        return JSON.parse(this.text());
    }
    return this._body;
} 

有没有人提示我如何使用 observables 获取响应对象。

【问题讨论】:

  • 成功 => { console.log('响应:' + 成功); },

标签: angular observable


【解决方案1】:

如果您在 Angular5 上使用 HttpClient 而不是 Http,那么我认为您可以删除 .map 并执行以下操作:

onSubmit() {
    if (this.form.valid) {
        this.authService.login(this.form.value)
            .subscribe(
                success => {
                    this.loginResponse = success;
                    console.log('Response: ' + success);
                },
                error => {
                    this.loginFailed = true;
                    setTimeout(() => {
                        this.loginFailed = false;
                    }, 3000);
                    console.error('ERROR login.component: ' + error);
                }
            );
    }
    this.formSubmitAttempt = true;
}

【讨论】:

    【解决方案2】:

    试试看

    this.authService.login(this.form.value).map(res => res.json()).subscribe(
        resp => {
         this.loginResponse = resp;
          console.log('Response: ' + this.loginResponse);
        },
        error=> //...
    

    如果使用 Angular 5,您应该使用 HttpClient 而不是已弃用的 Http 类。这样,您甚至不需要调用

    .map (res=>res.json())
    

    因为httpClient默认会自动将响应转成json格式

    【讨论】:

      【解决方案3】:

      response.json 是一个函数。你需要打电话给他们

      ...map( res => this.loginResponse = res.json() )
      

      【讨论】:

      猜你喜欢
      • 2018-10-01
      • 1970-01-01
      • 2020-09-01
      • 2020-03-16
      • 1970-01-01
      • 2016-11-28
      • 2018-10-12
      • 1970-01-01
      • 2019-10-15
      相关资源
      最近更新 更多