不等待根据 http get 请求从服务器获取数据 angular

not waiting for data to be fetched from server on http get request angular

嗨,我在端口 A 上有本地服务器,在端口 4200 上有一个 Web 应用程序 服务器有一些我通过 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();
      }
    }

在另一个 ts 文件中:

          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");

虽然有错误消息,但它们指的是 p 和 s 都未初始化的事实。

我已经通过在构造函数中执行此请求来检查来自服务器的数据是否正常,然后我将它们移至初始化函数。

谢谢

您的 p1p2 承诺没有任何已解决的值,因为 .then() 处理程序将 result 分配给 this.sthis.p,但它们 return 什么都没有,因此 p1p2 的解析值为 undefined。请记住,来自 .then() 处理程序的 return 值成为承诺的已解析值。

因此,当您这样做时:

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

所有values将是一个undefined的数组。相反,如果您这样做:

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

你应该看到你的价值观。或者,您实际上可以 return 来自 .then() 处理程序的那些值,然后每个承诺都会有一个已解析的值。

      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
        });