typescript 如何在组件方法中在 Angular 4 中进行同步调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46235060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make synchronous call in Angular 4 in component method
提问by Aakash Kumar
I have an Angular 4 login Application. I have written accessing logic in login.cmponent.ts file and accessing my login.service.ts file which in turn again calls an authentication service.
我有一个 Angular 4 登录应用程序。我在 login.cmponent.ts 文件中编写了访问逻辑并访问了我的 login.service.ts 文件,该文件又再次调用了身份验证服务。
When I call authenticate method from my login component, it returns false. By the time it executes remaining code then authentication service returns true because we know Angular run code in asynchronous way.
当我从登录组件调用身份验证方法时,它返回 false。当它执行剩余代码时,身份验证服务返回 true,因为我们知道 Angular 以异步方式运行代码。
This is my code:
这是我的代码:
Login Component Method:
登录组件方法:
this.loginService.setLoginData(
new LoginModel( this.userId, this.bankId, this.password )
).checkIfLoginSuccessfull();
Login.service Method:
Login.service 方法:
this.authService
.attemptAuth(credentials);
Authentication Service method:
认证服务方式:
attemptAuth(credentials): void {
this.restService
.post('/authenticate', credentials)
.subscribe(
data => this.setAuth(data.token),
err => this.destroy());
}
Code is working fine. But I want to get results the moment I finish executing checkIfLoginSuccessfull(). I know I am not doing or calling methods ( Observables correctly ).
代码工作正常。但是我想在我完成执行 checkIfLoginSuccessfull() 的那一刻得到结果。我知道我没有在做或调用方法(Observables 正确)。
Please help. :)
请帮忙。:)
回答by Micha? Ochociński
You should surround this
你应该围绕这个
this.restService
.post('/authenticate', credentials)
.subscribe(
data => this.setAuth(data.token),
err => this.destroy());
into "Observable.create".
进入“Observable.create”。
Observable.create(observer => {
this.restService
.post('/authenticate', credentials)
.finally(() => observer.complete())
.subscribe(
data => observer.next(data.token)
err => observer.error(err);
}
and then
接着
this.authService.attemptAuth(credentials).subscribe(...);