javascript - 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
解决方案
您的p1
andp2
承诺没有任何已解决的值,因为.then()
处理程序分配result
给this.s
and this.p
,但它们不返回任何内容,因此p1
and的已解决值p2
是undefined
。请记住,.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
});
推荐阅读
- angular - NGRX - 重置状态时,选择器返回重置前的值
- c# - 如何使用 gson 在 android studio 中反序列化 c# http 响应
- c++ - 如何在二进制文件上附加数据?
- java - ddl-auto update 创建的意外表
- java - 如何正确配置 Spring Validator (HibernateValidator)
- wpf - 调用线程无法访问此对象 (Dispatcher.CheckAccess)
- c# - 从 C# 中的 JSON 字符串中删除标记
- javascript - 在所有字段解析器完成后对graphql解析器的结果进行排序
- javascript - 使用正则表达式而不是滑动方法来操作 url
- javascript - 如何在 Vue.js 应用程序中正确下载 Excel 文件?