简体   繁体   English

Angular无法在数组属性中推送http响应

[英]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. 我正在使用httpclient从API获取一个JSON值,该API的ID在角度6中包含ID,并且正在另一个URL中传递该ID以获取将执行id.length次的每个ID的结果。 I have declared an array property and trying to push the second http result into array. 我已经声明了一个数组属性,并试图将第二个http结果推入数组。 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. json值不包含在方括号内。 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] 当我记录结果console.log(this.ChildStory)时,得到以下结果。) 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. 当您调用console.log时,该变量为null,但是当您稍后在控制台中查看它时,该变量将被填充,这就是为什么您可以在其中看到值的原因。 (As stated here ) (如前所述这里

What you could do in your getStory() function is to return an Observable. 您可以在getStory()函数中执行的操作是返回一个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: 然后,您可以在要使用检索到的值的任何地方订阅返回的Observable:

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. 我没有时间运行代码,因此可能会有一些“错误”,如果您发现任何问题,请告诉我,并将更新答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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