我正在嘗試處理從服務器獲取的 json 資料,但是當我嘗試執行 .forEach 時,它說我正在嘗試使用的資料未定義,而 console.log 顯示正確的值。
可能是什么問題,我是否錯過了某個地方的異步/等待?我是不是太早呼叫了資料處理函式?如果是,如何解決?
component.ts 的相關部分:
all: any;
constructor(private feedService: FeedService) { }
ngOnInit(): void {
this.fetchPosts();
console.log(this.all);
}
ngAfterContentInit() {
this.feedService.getTags(this.all.posts[0]);
}
async fetchPosts() {
(await this.feedService.getJSON(this.url)).subscribe((data) => {
console.log(data);
this.all = data;
console.log(this.all);
});
}
服務的相關部分:
constructor(private http: HttpClient) {
}
public async getJSON(url: string) {
return this.http.get<any>(url);
}
public async getTags(postData: any) {
let tags = [];
await postData['tags'].array.forEach(tag => { //This throws the error
tags.push(tag); //Uncomplete processign code, for now it
});
return tags;
}
這是控制臺輸出的螢屏截圖:
uj5u.com熱心網友回復:
添加this.all?.posts[0]
我認為問題是 this.all 是任何型別。當 this.all 為 null 或 undefined 時,this.all.posts 無法讀取,因為它會嘗試讀取undefined .posts,這是不可能的
uj5u.com熱心網友回復:
當您嘗試訪問“ngAfterContentInit”函式中的“this.all.posts[0]”時,“this.all”變數仍未設定,未定義。這個問題有不同的解決方案。其中之一是您可以在設定“this.all = data;”后呼叫“this.feedService.getTags(this.all.posts[0])”函式。
uj5u.com熱心網友回復:
this.feedService.getTags在定義this.all.posts[0]之前被呼叫。this.all
呼叫后的某個時間點將呼叫的回應fetchPosts分配給this.all。因為它是來自服務器的異步回應,所以您不能相信它會在任何時候回傳,即使在afterContentInit掛鉤觸發時也是如此。
您需要做的是等到訂閱fetchPosts命中并回傳資料。
all: any;
constructor(private feedService: FeedService) { }
ngOnInit(): void {
this.fetchPosts();
}
async fetchPosts() {
this.feedService.getJSON(this.url).subscribe((data) => {
this.all = data;
// It would be wise to add handling for posts being undefined here.
this.feedService.getTags(this.all.posts[0]);
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/534828.html
