Http获取响应更新HTML,但在控制台中给出了未定义的错误 [英] Http Get Response Updates HTML but giving undefined error in console
问题描述
当我使用 HttpClient 用响应Obj更新我的 html 时,它会更新值,但会出现多个错误。
When I am updating my html with the response Obj using HttpClient it updates the values but gives multiple errors.
文件名-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
}
文件名-信息中心。 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"> </div>
<div class="row m-t p-t">
<div class="col-xs-12"> </div>
</div>
</div>
有关控制台错误的详细信息:
Details about errors in console:
。
推荐答案
您的错误很可能是因为Angular尝试评估 user.active
在 get
请求完成之前。
Your error is likely because Angular attempts to evaluate user.active
before the get
request completes.
您可以更新 {{user.active}}
包含?
(称为安全导航操作符):
You can update {{ user.active }}
to include a ?
(known as the safe navigation operator):
{{ user?.active }}
Angular安全导航运算符( ?)是一种流畅而便捷的方法,可以防止属性路径中的空值和未定义值。
The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths.
您可以改用 ngIf
避免在检索数据之前渲染容器。即:
You could instead use ngIf
to avoid rendering your container until the data is retrieved. i.e.:
<div class="container-fluid text-center" *ngIf="user">
这篇关于Http获取响应更新HTML,但在控制台中给出了未定义的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!