[英]Bind JSON http response to Angular 6 components
我從我的HttpClient GET方法獲得JSON響應以下
{
shortDescription: "3",
promotionName: "2",
highResolutionImage: "4",
lowResolutionImage: "5",
promotionOrChallengeCode: "aaa"
}
Promotion.ts
export interface IPromotion
{
PromotionOrChallengeCode:string;
PromotionName:string;
ShortDescription:string;
HighResolutionImage:string;
LowResolutionImage:string;
}
在我的Component類中
promotion:IPromotion;
onSubmit() : void {
this.httpClient.get('http://localhost:8080/api/search/'+this.pcode )
.subscribe((response:IPromotion) =>
{
console.log(response);
this.promotion = response;
console.log(this.promotion.PromotionOrChallengeCode);
});
}
在瀏覽器控制台中,我可以查看JSON響應(第一個控制台語句的輸出)。 並且第二個控制台語句的輸出顯示為“未定義”
讓我知道如何讀取JSON數據並綁定到HTML元素
以下是我正在使用的當前Angular版本:
C:\Users\893108>ng -v
_ _ ____ _ ___
/ \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|
/ ? \ | '_ \ / _` | | | | |/ _` | '__| | | | | | |
/ ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | |
/_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___|
|___/
Angular CLI: 6.1.2
Node: 8.11.3
OS: win32 ia32
Angular:
...
Package Version
------------------------------------------------------
rxjs 6.2.2
typescript 2.7.2
問題是您的json接口需要與api響應具有相同的大小寫。 另外,您需要將HttpClient傳遞給接口的通用簽名。
export interface IPromotion
{
promotionOrChallengeCode: string;
promotionName: string;
shortDescription: string;
highResolutionImage: string;
lowResolutionImage: string;
}
promotion:IPromotion;
onSubmit() : void {
this.httpClient.get<IPromotion>('http://localhost:8080/api/search/'+this.pcode )
.subscribe((response:IPromotion) =>
{
console.log(response);
this.promotion = response;
console.log(this.promotion.promotionOrChallengeCode);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.