简体   繁体   English

如何在我的 ngOnInit 方法上不使用异步来等待我的呼叫?

[英]How can i wait for my call without using async on my ngOnInit method?

I have the following code.我有以下代码。 To wait for my async call I am using the following要等待我的异步调用,我正在使用以下

 testi() {
   return new Promise((resolve,reject) => {
     resolve(true);
   })
  }


  async ngOnInit() {
    let pp = await this.testi();
    console.log('pp', pp);

}

is there any other way with which I can wait for the call here without adding async notation on my ngOnInit method?有没有其他方法可以在这里等待调用而不在我的ngOnInit方法上添加async表示法?

You can use then instead of await :您可以使用then而不是await

testi() {
  return new Promise((resolve,reject) => {
    resolve(true);
  });
}

ngOnInit() {
  this.testi()
    .then(value => console.log(`pp: ${value}`))
}

If you are writing Typescript code, chances are that your compiled code will uses then instead of await .如果您正在编写 Typescript 代码,那么您的编译代码可能会使用then而不是await It is the "old" way of using promises.这是使用 Promise 的“旧”方式。

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Promise/then https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

You can have a separated method that handles all the async parts and its result, and within your ngOnInit() you just call that method.您可以有一个单独的方法来处理所有异步部分及其结果,并在您的 ngOnInit() 中调用该方法。

async testi() {
  let pp = await new Promise((resolve,reject) => {
    resolve(true);
  })

  console.log('pp', pp)
}

ngOnInit() {
  this.testi();
}

You can subscribe to it..你可以订阅它。。

 ngOnInit() {
    this.testi().subscribe((pp:any) => {
       console.log('pp', pp);
    }
}

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

相关问题 如何在测试之前等待异步ngOninit完成 - How can I wait for async ngOninit to complete before testing Angular 4:为什么我不能在ngOnInit()中调用公共函数? - Angular 4: why can't I call a public function in my ngOnInit()? 在 ngOnInit 中等待来自 get 调用的数据时,如何显示微调器? (角度 15) - How can i show a spinner while waiting for data from a get call inside my ngOnInit ? (Angular 15) Angular 2如何使变量等待异步值? - Angular 2 how can i make my variable wait async for values? 如何让我的警卫在解析器中等待 http 呼叫? - How can i make my guard to wait for http call in resolver? 如何在ngOnInit中使用订阅等待API调用完成? - How to wait for an API call using subscribe to finish in ngOnInit? 我如何等待异步管道完成并在不订阅的情况下调用另一个函数 - How can I wait async pipe to finish and call another function after, without subscribing 如何在 ngOnInit 中调用事件方法 - how to call method of event in ngOnInit 如何调用 Angular 中任何组件的特定公共方法,例如 `ngOnInit` 的工作原理 - How can I call a specific public method of any component in Angular, like how `ngOnInit` works 我如何在其他方法中等待异步结果 - How can i wait for async result in other method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM