简体   繁体   English

角度等待,直到函数执行完毕

[英]Angular Wait until function has been executed

I am currently programming a page in Angular. 我目前正在Angular中编写页面。 As soon as a page is called, the OnInit method is used to execute a function that initializes multiple variables. 一旦调用页面,就会使用OnInit方法执行初始化多个变量的函数。 When this is done, an if query should be used to check whether a variable has a certain value (which is initialized in the function before). 完成此操作后,应使用if查询来检查变量是否具有某个值(该值在之前的函数中已初始化)。

How can I make sure that the if query is not made until the function is finished? 如何确保函数完成之前不进行if查询?

And is it possible to execute a function when starting the app? 启动应用程序时是否可以执行功能?

It might be better for you to initialize some of your variables in the constructor for the component and then do your if check in the onInit function. 您最好在组件的构造函数中初始化一些变量,然后检查onInit函数。 The lifecycle hook for Angular has the constructor code executed before the onInit function. Angular的生命周期挂钩在onInit函数之前执行了构造函数代码。

Add the query stuff within the function? 在函数中添加查询内容? or Convert the function into maybe a subscription or promise and then do something once that resolves? 或将函数转换为订阅或Promise,然后在解决后执行一些操作?

Observable.subscribe(value=> { // do something here }); Observable.subscribe(value => {//在这里做某事});

Promise.then(value => // do something here); Promise.then(value => //在这里做些事情);

or even maybe call that function or that code within the function you need to wait to complete. 甚至可以调用该函数或您需要等待完成的函数中的该代码。

You can execute a function when starting the application bootstrap. 您可以在启动应用程序引导程序时执行功能。

You have to revert to promise for that and follow this -- may have changed for v6, but should be similar concept. 您必须对此做出承诺并遵循此原则-v6可能已更改,但应该是类似的概念。

Angular 2: Call service before bootstrap Angular 2:引导前呼叫服务

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

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