问题描述
当我使用 HttpClient 使用响应 Obj 更新我的 html 时,它会更新值但会出现多个错误.
文件名 - auth-service.ts.
import { any } from 'codelyzer/util/function';从'@angular/core'导入{可注射};从'@angular/common/http' 导入 { HttpClient };@Injectable()导出类 AuthService {构造函数(私有httpClient:HttpClient){}得到() {返回 this.httpClient.get):{{ user?.active }}
Angular 安全导航操作符 (?.) 是防止属性路径中出现 null 和 undefined 值的流畅而便捷的方法.
您可以改为使用 ngIf
来避免在检索到数据之前呈现您的容器.即:
When I am updating my html with the response Obj using HttpClient it updates the values but gives multiple errors.
File Name - 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'
});
}
};
File Name - 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;
}
);
}
}
The Response Obj is
{
"firstName": "xyz",
"lastName": "abc",
"active": true
}
File Name - 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"> </div>
<div class="row m-t p-t">
<div class="col-xs-12"> </div>
</div>
</div>
Details about errors in console:
.
解决方案 Your error is likely because Angular attempts to evaluate user.active
before the get
request completes.
You can update {{ user.active }}
to include a ?
(known as the safe navigation operator):
{{ user?.active }}
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 Get Response 更新 HTML 但在控制台中给出未定义的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
08-06 15:02