简体   繁体   中英

Angular could not push http response in array property

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.stack.imgur.com/1korE.jpg [1]

At the moment when you call your console.log, the variable is null, but when you look at it at a later stage in the console, that variable is populated, which is why you can see the values there. (As stated here )

What you could do in your getStory() function is to return an Observable. It could look somewhat like:

getStories() {
    return new Observable<Stories[]> ( (observer) => {
        this.http.get<Stories[]>('URL').subscribe((response) => {

            this.Story = response;
            let storiesCalls = [];
            for (let i = 0; i < this.Story.length; i++) {
                storiesCalls.push(this.http.get('URL' + this.Story[i]+'.json'));
            }

            forkJoin(storiesCalls).subscribe((childStories) => {
                observer.next(childStories);
                observer.complete();
            });

        }, (error) => {
            console.log("Error occurred" + error)
            observer.error(error);
            observer.complete();
        });
    });
}

Then you can subscriber to the returned Observable wherever you want to use the retrieved values:

hackerStoriesServiceInstance.getStories().subscribe((childStories) => {
    //do stuff with childStories object
}

I did not have time to run the code, so there might be some "bugs", if you find any issue let me know and will update the answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM