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;
}
);
}
}
Response Objは-
{
"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"> </div>
<div class="row m-t p-t">
<div class="col-xs-12">
</div>
</div>
</div>
回答:
回答№1の場合は3簡単に更新できます {{ user.active }}
を含める ?
。すなわち:
{{ user?.active }}
Angularが評価しようとするため、エラーの可能性が高い user.active
の前に get
要求が完了します。
これは、 安全なナビゲーションオペレータ:
Angular safe navigation operator(?。)は、プロパティパスのnullおよび未定義の値から保護するための流で便利な方法です。
代わりに ngIf
データが取得されるまでコンテナをレンダリングしないようにします。すなわち:
<div class="container-fluid text-center" *ngIf="user">
回答№2の場合は0
コンポーネントに応答を返すには、マップ関数を使用する必要があります。このコードをservice getに置き換えます。
get() {
return this.httpClient.get<any>("/capi/v2/users/me")
.map((resp) => resp)
.catch((error) => error);
}