简体   繁体   English

等待承诺Angular 2

[英]Wait to Promise Angular 2

First of all I want to explain that I have read a lot of answers, and I understand that it's wrong to block the thread to wait a response. 首先,我想解释一下我已经阅读了很多答案,并且我了解阻止线程等待响应是错误的。 But I have an issue that is not that simple to solve. 但是我有一个问题并不容易解决。

I have an advanced project, where I have a function on a session service that is getAuthenticationKey():string I have used it a lot from differents parts of the code (to call rest functions, etc.), and I made it as an ordinary function because I thought that this value will be there or not. 我有一个高级项目,其中在会话服务上有一个功能为getAuthenticationKey():string我在代码的不同部分(例如调用剩余函数等)使用了很多功能,并将其作为普通函数,因为我认为此值将存在或不存在。

Now we have made some changes, and the getAuthenticationKey will have to call a rest function to refresh the key if it's necessary. 现在我们进行了一些更改,如果必要, getAuthenticationKey将必须调用rest函数来刷新密钥。

So the problem is that I understand that the best way to do that is to make a promise and refactor the whole project, but this is too expensive in terms of hours, because I have to make promises for that function and all others that depends of that function (almost all the application), and considering that the refresh is a fast operation and is called once a day or a week, there is any way to fix this without refactoring all the project? 因此,问题在于,我了解做到这一点的最佳方法是做出承诺并重构整个项目,但这在小时数方面太昂贵了,因为我必须对该功能以及所有其他依赖于此的功能做出承诺。该功能(几乎所有应用程序),并且考虑到刷新是一项快速操作,并且每天或每周调用一次,是否有任何方法可以解决此问题而无需重构所有项目?

You can probably keep your code as it is, just add a periodic checker ( setInterval(...) ) that will update the authenticationKey if necessary. 您可能可以保持您的代码不变,只需添加一个定期检查器( setInterval(...) ),该检查器将在必要时更新authenticationKey If you know the lifetime of the key, you can just use setTimeout(...) instead of periodic checking. 如果知道密钥的生存期,则可以只使用setTimeout(...)而不是定期检查。

I solve this problem using a Resolver, since I check the authentication when a page is loaded. 我使用解析器解决了此问题,因为我在加载页面时检查身份验证。 In the resolver I check the auth against a rest service and store the result in a service. 在解析器中,我针对其余服务检查身份验证,并将结果存储在服务中。

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

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