[英]How to convert JSON response to array of angular objects within service?
編輯:無需回答,問題出在其他地方。 我道歉 :(
我需要getHeroes()返回一個數組'Hero'。 它正在使用教程的內存中數據,但是當我使用django rest API時失敗。
hero.ts
export class Hero {
id: number;
name: string;
}
hero.service.ts
getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl).pipe(
map(response => response['heroes']),
tap(_ => this.log('fetched heroes')),
catchError(this.handleError<Hero[]>('getHeroes', []))
);
}
來自API的JSON響應
{
"heroes": [
{
"id": 1,
"name": "hero1"
},
{
"id": 2,
"name": "hero2"
}
]
}
您可以在組件內部使用subscribe
:
import { Hero } from "./heroComponent";
export class SomeComponent implements OnInit {
heroes: Hero;
constructor(private serv: YourService) { }
ngOnInit() {
this.serv.getHeroes().subscribe(serv => {
this.heroes = serv
console.log(this.heroes);
});
}
}
當然,請更改一些內容以使其適合您的代碼。 它應該將您的JSON映射到Object。
查看以下任何幫助:
這可能更符合您的要求: https : //nehalist.io/working-with-models-in-angular/
其他
https://coursetro.com/posts/code/171/Angular-7-Tutorial---Learn-Angular-7-by-Example (向下滾動至其中的HTTP服務部分)
有兩個選項(此處為簡潔起見,省略了錯誤處理):
選項1:將結果視為any
,並將heroes
屬性投射給Hero[]
getHeroes(): Observable<Hero[]> {
return this.http.get<any>(this.heroesUrl).pipe(
map(res => res.heroes as Hero[])
);
}
選項2(首選):創建一個模型(例如HeroResult
),該模型表示服務器實際返回的具有完全類型安全性的模型
export class HeroResult {
heroes: Hero[];
}
getHeroes(): Observable<Hero[]> {
return this.http.get<HeroResult>(this.heroesUrl).pipe(
map(res => res.heroes)
);
}
對不起。 當我看到django API發送的XHR響應時,出現了CORS問題。 我不必更改代碼。 只是不得不允許在哥倫比亞的CORS。 很抱歉占用您的時間。 謝謝你的建議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.