0

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]

5
  • You are logging the ChildStory before 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 using Promise.all() or try various methods provided by rxjs Commented Dec 31, 2018 at 20:42
  • But I can able to see the response in browser console. (i.sstatic.net/1korE.jpg ). If the URL calls aren't finished then Ican't see the result right. Only when I give array postion in the property it gives undefined. Commented Dec 31, 2018 at 21:13
  • The output at the console comes first, the URLs finish later. If you put a console.log after pushing to ChildStpry, you can see that the result is actually pushed to the array. Commented Dec 31, 2018 at 21:18
  • I am trying to log the results after for loop execution. Can you please tell me then where i can place console.log in the above code. That would be helpful. Commented Dec 31, 2018 at 21:29
  • Put it just after this.ChildStory.push(response) Commented Dec 31, 2018 at 21:39

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for coming forward to help me out. I am getting error in above code: expected 0-1 argument but got 2. can u help me resolve it.
I edited my code. There were some brackets missing/too much. Please retry and let me know. Also please post the exact stacktrace of the error, else it will be to hard to guess the problem. I tried the above example with one of my APIs and adapted it to your code. It should be working now. Or at least it shouldn't require too much adaptation. Also note that variables should be named in camelCase. Also note that you had an error in your for statement. It should go from i=0 to i<this.Story.length, and not <=

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.