如何在组件方法中在Angular 4中进行同步调用

Aak*_*mar 3 typescript angularjs-directive angular2-observables angular

我有一个Angular 4登录应用程序.我已经在login.cmponent.ts文件中编写了访问逻辑并访问了我的login.service.ts文件,该文件又调用了一个身份验证服务.

当我从登录组件调用authenticate方法时,它返回false.当它执行剩余代码时,身份验证服务返回true,因为我们以异步方式知道Angular运行代码.

这是我的代码:

登录组件方法:

this.loginService.setLoginData(
    new LoginModel( this.userId, this.bankId, this.password )
  ).checkIfLoginSuccessfull();
Run Code Online (Sandbox Code Playgroud)

Login.service方法:

this.authService
  .attemptAuth(credentials);
Run Code Online (Sandbox Code Playgroud)

验证服务方法:

attemptAuth(credentials): void {

  this.restService
    .post('/authenticate', credentials)
    .subscribe(
    data => this.setAuth(data.token),
    err => this.destroy());

}
Run Code Online (Sandbox Code Playgroud)

代码工作正常.但是我想在执行checkIfLoginSuccessfull()的那一刻得到结果.我知道我没有做或调用方法(Observables正确).

请帮忙.:)

Mic*_*ski 5

你应该包围这个

this.restService
    .post('/authenticate', credentials)
    .subscribe(
      data => this.setAuth(data.token),
      err => this.destroy());
Run Code Online (Sandbox Code Playgroud)

进入"Observable.create".

Observable.create(observer => {
  this.restService
    .post('/authenticate', credentials)
    .finally(() => observer.complete())
    .subscribe(
      data => observer.next(data.token)
      err => observer.error(err);
 }
Run Code Online (Sandbox Code Playgroud)

然后

this.authService.attemptAuth(credentials).subscribe(...);
Run Code Online (Sandbox Code Playgroud)