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

atu*_*hra -1 angular2-template angular2-services angular 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'
        });
      }
    };
Run Code Online (Sandbox Code Playgroud)

文件名-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;
              }
            );
        }
    }
Run Code Online (Sandbox Code Playgroud)

响应对象是

{
    "firstName": "xyz",
    "lastName": "abc",
    "active": true
}   
Run Code Online (Sandbox Code Playgroud)

文件名-dashboard.component.html

    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'
        });
      }
    };
Run Code Online (Sandbox Code Playgroud)

有关控制台错误的详细信息:

在这里描述

Kir*_*kin 5

您的错误很可能是因为Angular user.activeget请求完成之前尝试评估。

您可以更新{{ user.active }}以包含?(称为安全导航运算符):

{{ user?.active }}
Run Code Online (Sandbox Code Playgroud)

Angular安全导航运算符(?。)是防止属性路径中的空值和未定义值的一种流畅便捷的方法。

相反,您可以使用它ngIf来避免呈现容器,直到检索到数据为止。即:

<div class="container-fluid text-center" *ngIf="user">
Run Code Online (Sandbox Code Playgroud)