I'm trying to process the json data I get from a server but when I try to do a .forEach, on it it says that the data I'm trying to work with is undefined while the console.log displays the correct values.
What could be the problem, am I missing an async/await from somewhere? Am I calling the data processing function too early? If yes how could it be solved?
Relevant parts of the 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);
});
}
Relevant parts of the service:
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;
}
And here is a screenshot of the console output:
CodePudding user response:
add this.all?.posts[0]
I think problem is that this.all is any type.
When this.all is null or undefined then this.all.posts cannot be read as it will try to read undefined.posts which is not possible
CodePudding user response:
When you try to access the "this.all.posts[0]" in "ngAfterContentInit" function "this.all" variable is still not set, is undefined. There are different solutions to this problem. One of them is you can just call the "this.feedService.getTags(this.all.posts[0])" function after you set the " this.all = data;"
CodePudding user response:
this.feedService.getTags
is being called with this.all.posts[0]
before this.all
is defined.
The response from the fetchPosts
call is assigned to this.all
at some point after the call is made. Since it's an asynchronous response from a server, you can't trust that it will have returned at any point, even when the afterContentInit
hook fires.
What you need to do is wait until the subscription in fetchPosts
hits and returns with data.
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]);
});
}