0
votes

I did create my own Observable service that return current tracks of a player.

I'm subscribing to this service on my Angular component this way:

this.playerSubscription = this.player
      .player(playlist)
      .subscribe(
        playerInfo => this.playerInfo = playerInfo,
        error => this.router.navigate(['login'], { queryParams: { error: 'expired_token' }})
      );

As you can see, when I have an error, I redirect the user to the login page.

The problem is when I do login after a previous error, the subscription returns to me the lastest error sequence and I gonna redirected again to the login page.

On my service, I'm using the BehaviorSubject and doing subject.next(message) to valid sequences, and subject.error(error) to send an error sequence.

How can I forget about the last error after resubscribing to my observable?

Thank you!

UPDATE 1:

I did some new tests here and it only works when I create a new subject every time I subscribe, like bellow:

player(playlist: IPlaylist, fromBegin: boolean): Observable<IPlayerInfo> {

    this._player = new BehaviorSubject<IPlayerInfo>({ status: PlayerStatuses.LOADING });

    ... more code here ...

    return this._player.asObservable();
  }

Nevermind if it's a Subject or a BehaviorSubject.

Is this a good practice?

1
I would do redirect to login inside you player method logic right before subject.error call or use auth guard for players route. - Andzej Maciusovic
I don't think it's a good idea to add a router inside a service. I don't think it's a service responsibility to redirect the user for the login page. - Paulo GR

1 Answers

0
votes

How can I forget about the last error after resubscribing to my observable?

Use Subject instead of BehaviorSubject.

var subject = new Rx.Subject();

BehaviorSubject is one of Subject variant which remember current value. So if you do not want to get the latest value every time you subscribe, use Subject.