Search code examples
angulartypescriptrouterlinkrxjs-observables

Angular routerLink only triggers ngOnInit once


I have found several questions similar to mine, but the big part are related to params, the answers didn't help me to solve my issue. Basically the problem is the following: Once the user logs in, the user is able to visualize his/her username in the navbar, when they click on it, the page takes the user to the profile page, the first time it works perfectly, when the user logs out and logs in with different username the information of the old user is still there unless the page is refreshed.

Service Account

getUserInformation(userId: number) {
if (!this.userInformation$) {
  this.userInformation$ = this.http.post<any>(this.baseUrlGetUserInfo, { userId }).pipe(shareReplay());
}
return this.userInformation$;
}

On init method

ngOnInit() {
this.route.params.subscribe(params => {
  this.loaderSpinner = true;
  // tslint:disable-next-line: radix
  // this.userId = this.accntService.currentUserId;
  // tslint:disable-next-line: radix
  this.accntService.currentUserId.subscribe(res => {
    this.userId = res;
  });
  // tslint:disable-next-line: radix
  this.userInformation$ = this.accntService.getUserInformation(parseInt(this.userId));
  this.userInformation$.subscribe(result => {
    this.userInformation = result.userInformation;
    console.log(this.userInformation);
    this.loaderSpinner = false;
  }, error => {
    this.loaderSpinner = false;
    console.error(error);
  });
});
}

Navbar HTML

<a [routerLink]="['/profile']" class="nav-link" *ngIf="(userName$ | async) as userName">
          {{userName}}
        </a>

Can somebody help me with this?

Thanks in advance.


Solution

  • Here is the problem, I found the issue. Basically the error was in the onDestroy.

    private getUserInfo(): void {
    this.loaderSpinner = true;
    this.accntService.currentUserId.pipe(takeUntil(this.$ondestroy)).subscribe(res => {
      this.userId = res;
    });
    
    this.accntService.getUserInformation(this.userId).pipe(takeUntil(this.$ondestroy)).subscribe(response => {
      this.userInformation = response.userInformation;
      this.loaderSpinner = false;
    }, () => {
      this.loaderSpinner = false;
    });
    }
    
    ngOnInit() {
    this.getUserInfo(); }
    
    ngOnDestroy() {
    this.$ondestroy.next(true);
    }