I am getting a json value from API using httpclient which contains ID in angular 6 and I am passing that ID in another url to get result for each ID which will execute id.length times. I have declared an array property and trying to push the second http result into array. When I log out the result, I can see that results are not getting inserted within square beacket; json values are away from the sqaure bracket. Please find below image for the result. Can anyone please give me solution how to push value properly in array property.
Angular Service:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { Stories } from '../stories';
import { error } from 'util';
import { tap, map, catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class HackerStoriesService {
Story: Array<any> = [];
ChildStory: Array<object> = [];
constructor(private http: HttpClient) {
}
getStories(){
this.http.get<Stories[]>('URL')
.subscribe((response) => {
this.Story = response;
for(let i=0;i<=this.Story.length;i++){
this.http.get('URL'+this.Story[i]+'.json')
.subscribe((response)=> {
this.ChildStory.push(response)
})
}
console.log(this.ChildStory)
return this.ChildStory;
},
(error) => {console.log("Error occurred" + error)},
()=> {console.log("The subscription is completed")});
}
}
Result:
When I log the result console.log(this.ChildStory), I am getting following result.) https://i.sstatic.net/1korE.jpg [1]
ChildStorybefore your URL calls are finished. Please keep in mind how the callback function works. In case if you want to do the things synchronously, you can try usingPromise.all()or try various methods provided byrxjsthis.ChildStory.push(response)