Angular4组件方法中如何同步调用

How to make synchronous call in Angular 4 in component method

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

当我从我的登录组件调用身份验证方法时,它 returns 错误。当它执行剩余代码时,身份验证服务 returns true 因为我们知道 Angular 运行 异步方式的代码。

这是我的代码:

登录组件方法:

this.loginService.setLoginData(
    new LoginModel( this.userId, this.bankId, this.password )
  ).checkIfLoginSuccessfull();

Login.service方法:

this.authService
  .attemptAuth(credentials);

身份验证服务方法:

attemptAuth(credentials): void {

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

}

代码运行良好。但我想在执行完 checkIfLoginSuccessfull() 时立即获得结果。我知道我没有做或调用方法(正确的 Observables)。

请帮忙。 :)

你应该包围这个

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

进入"Observable.create".

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

然后

this.authService.attemptAuth(credentials).subscribe(...);