Angular 5 / Typescript / RxJS - 从Observable获取数据

时间:2018-02-20 15:09:10

标签: angular observable

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

G.Ac down               Shared down regulated   Mc.Ac down 
GENE:JGI_V11_619450303  GENE:JGI_V11_619450303  GENE:JGI_V11_3219080103
GENE:JGI_V11_2644330202                         GENE:JGI_V11_534070103
GENE:JGI_V11_1064490203 GENE:JGI_V11_1064490203 GENE:JGI_V11_3146980103
GENE:JGI_V11_3327160202                         GENE:JGI_V11_3018650102
GENE:JGI_V11_3179550203                         GENE:JGI_V11_3018650202
GENE:JGI_V11_3050490103                         GENE:JGI_V11_3146980203
GENE:JGI_V11_1064490103 GENE:JGI_V11_1064490103 GENE:JGI_V11_2378650103
GENE:JGI_V11_1044440103                         GENE:JGI_V11_2378650303
GENE:JGI_V11_3277080303 GENE:JGI_V11_3277080303 GENE:JGI_V11_3146980303

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

console.log的输出是:

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;            
  }

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

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

如果您使用HttpClient而不是Http使用Angular5,那么我认为您可以删除.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 :(得分:0)

试试

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格式