首页 > 解决方案 > not waiting for data to be fetched from server on http get request angular

问题描述

hi i have local server on port A and single web app on port 4200 server has some data i request via http

data.service.ts:

    export class DataService {
      constructor(private httpClient: HttpClient) {}

      async get_p() {
        return await this.httpClient.get<object[]>('/some api').toPromise();
      }

      async get_s() {
        return await this.httpClient.get<object[]>('/some api').toPromise();
      }
    }

in another ts file :

          init() {
            let p1 =this.dataService.get_s().then((result) => {this.s = 
             result; } ) ;
            let p2 = this.dataService.get_p().then((result) => {this.p = 
             result; } );

            Promise.all([p1, p2]).then(values => {
              console.log(values); ///undefined
            });

            console.log("not waiting for data");

well ther are error messages but they refer to the fact that both p and s are not intialized.

i have already checked that data comes ok from server by doing this requests in constructor and then i moved them to init function.

thank you

标签: javascriptangularrestes6-promise

解决方案


您的p1andp2承诺没有任何已解决的值,因为.then()处理程序分配resultthis.sand this.p,但它们不返回任何内容,因此p1and的已解决值p2undefined。请记住,.then()处理程序的返回值成为 promise 的解析值。

因此,当您这样做时:

Promise.all([p1, p2]).then(values => {
    console.log(values); ///undefined
});

所有values将是一个数组undefined。相反,您可以这样做:

Promise.all([p1, p2]).then(values => {
    console.log(this.p, this.s);
});

你应该看到你的价值观。或者,您也可以实际从.then()处理程序返回这些值,然后每个 Promise 都会有一个已解析的值。

      init() {
        let p1 =this.dataService.get_s().then((result) => {
            this.s = result; 
            return result;  // set resolved value of promise
        });
        let p2 = this.dataService.get_p().then((result) => {
             this.p = result; 
             return result;  // set resolved value of promise
        });

        Promise.all([p1, p2]).then(values => {
          console.log(values); // will show the resolved values now
        });

推荐阅读