Http获取响应更新HTML但在控制台中给出了未定义的错误

时间:2017-09-08 11:38:37

标签: angular angular2-template angular2-services angular4-httpclient

当我使用HttpClient使用响应Obj更新我的Html时,它会更新值但会出错。请帮助!

文件名 - auth-service.ts

import { any } from 'codelyzer/util/function';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class AuthService {

  constructor(private httpClient: HttpClient) { }
  get() {
    return this.httpClient.get<any>('/capi/v2/users/me', {
      observe: 'body',
      responseType: 'json'
    });
  }
};

文件名 - dashboard.component.ts

import { AuthService } from './../../services/api/auth-service';

import { Component, Injectable, OnInit } from '@angular/core';

@Component({
    selector: 'app-dashboard',
    templateUrl: './dashboard.component.html'
})

@Injectable()
export class DashBoardComponent implements OnInit {
    user;
    constructor(private authService: AuthService) {};

    ngOnInit() {
         this.authService.get()
        .subscribe(
          (response) => {
              this.user = response;
          }
        );
    }
}

响应对象是 -

{

"firstName": "xyz",
"lastName": "abc",
"active": true

}

文件名 - dashboard.component.html

<div class="container-fluid text-center">
    <h1 class="bold m-t m-b-xs">Hey there!</h1>
    <h3 class="m-b">How are you doing today?</h3>


    {{ user.active }}

    <div class="block clear m-a">&nbsp;</div>

    <div class="row m-t p-t">
      <div class="col-xs-12">
      </div>
    </div>
</div>

控制台enter image description here

出错

2 个答案:

答案 0 :(得分:4)

您只需更新{{ user.active }}即可添加?。即:

{{ user?.active }}

您的错误可能是因为Angular在user.active请求完成之前尝试评估get

这称为safe navigation operator

  

Angular安全导航操作符(?。)是一种流畅且方便的方法,可以防止属性路径中的空值和未定义值。

您可以使用ngIf来避免在检索数据之前呈现容器。即:

<div class="container-fluid text-center" *ngIf="user">

答案 1 :(得分:0)

您需要使用map函数来返回对组件的响应。将此代码替换为service get。

get() {
  return this.httpClient.get<any>('/capi/v2/users/me')
    .map((resp) => resp)
    .catch((error) => error);
}