Angular 2中的Observable emit/error函数在调用一次error函数后就会被忽略



我有一个API登录服务,使用http服务来执行登录逻辑(LoginApiService, login- API .service.ts):

login(data: LoginCredentials): Observable<LoginResult> {
  let body = JSON.stringify( data );
  let headers = new Headers({ 'Content-Type': 'application/json' });
  let options = new RequestOptions({ headers: headers });
  return this.http.post(`${this.getBaseUrl()}/login`, body, options)
                  .map(this.extractData)
                  .catch(function(error: Response){
                    return Observable.throw(error); // IF YOU TRY TO LOGIN WITH WRONG CREDENTIALS, AN ERROR WILL BE THROWN
                  });
}

此服务在全局服务类(authService, auth.service.ts)中使用:

login(data: LoginCredentials): void {
    this.api.login(data).subscribe(
    data => {
      this.isLoggedIn = true;
      this.group = data.group;
      this.Login.emit(new LoginResult(this.group)); // THE CALL OF THIS FUNCTION IS IGNORED IF THE "this.Login.error" FUNCTION HAS BEEN CALLED BEFORE
    },
    error => {
      this.Login.error(error); // THIS IS IGNORED TOO, IF IT WAS CALLED BEFORE
    }
  );
}

Component (LoginComponent, login.component.ts):

ngOnInit() {
  this.LoginSubscription = this.authService
    .Login
    .subscribe( // THE EVENTS ARE NOT FIRED IF THE ERROR EVENT HAS BEEN FIRED BEFORE ONCE
      data => {
        if ( this.authService.isLoggedIn ) {
          this.router.navigate(['/dashboard']);
        }
      },
      error => {
        this.handleError(error);
      }
    );
}
login() {
  this.authService.login( new LoginCredentials(this.user, this.password) );
}
模板(login.component.html):

<div>
  <label>User: </label>
  <input [(ngModel)]="user" placeholder="user">
</div>
<div>
  <label>Password: </label>
  <input [(ngModel)]="password" placeholder="password" type="password">
</div>
<p>
  <button (click)="login()">Login</button>
</p>

如果login可观察对象的error事件函数之前被调用过,在此之后调用emit和/或error函数将被忽略。

  • 使用正确的登录凭据,模拟API使用HTTP响应代码200,一切正常
  • 如果凭据错误,HTTP响应是500在再次调用API(使用正确或错误的凭据)之后事件不再被触发

这意味着:如果您使用了错误的登录凭据,您将无法再次尝试,除非重新加载页面。

  • 我使用可观察对象的想法是错误的?

  • 为什么事件流在调用错误函数后挂起一次?

  • 谁能给我一个提示来解决这个问题(某种)工作区。)?

这是因为你出错了你的EventEmitter。eventemitter基本上是可观察对象,当它的观察者调用errorcomplete时,它关闭可观察对象。关闭的可观察对象将按照设计停止发出事件。

要解决您的问题,请删除LoginComponent中的this.Login.error(error);。这样你就不会关闭那个EventEmitter。尝试用逻辑来替换它,告诉用户凭据错误或其他消息来描述错误。

最新更新