简体   繁体   English

Angular routerLink 只触发 ngOnInit 一次

[英]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在 init 方法上

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导航栏 HTML

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

Can somebody help me with this?有人可以帮我解决这个问题吗?

Thanks in advance.提前致谢。

Here is the problem, I found the issue.这是问题所在,我发现了问题。 Basically the error was in the onDestroy.基本上错误出在 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM