Angular routerLink causes ngOnInit to be triggered only once

I have come across numerous questions similar to mine, however, the majority are linked to params. The answers provided did not aid in resolving my specific issue. Essentially, the problem I am facing is as follows: After a user logs in, their username is displayed in the navbar. When the user clicks on it, they should be taken to their profile page. Initially, this functionality works perfectly. However, when the user logs out and then logs back in with a different username, the information from the previous user remains visible 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$;
}

OnInit 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>

Could someone provide assistance with this issue?

Thank you in advance.

Answer №1

I have identified the problem and located the issue. The error was actually occurring in the onDestroy method.

private retrieveUserInfo(): 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.retrieveUserInfo(); }

ngOnDestroy() {
this.$ondestroy.next(true);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Storing information from JSON into an object

I am encountering an issue regarding transferring data from JSON to an object. Although this solution is functional, it is not entirely satisfactory. Take a look at the service. Is there an improved method for handling data conversion from this JSON to an ...

How to retrieve the value of a variable accessible to all users in Angular?

In my code, I am working with a service variable called Users. Service: Users:BehaviorSubject<Array<any>> = new BehaviorSubject([]); I am updating the values in the component using this code: this.Service.Users.next([...this.Service.User ...

Obtain a filtering dropdown list directly from the database within Ag-grid

Currently in my interface, I am attempting to implement a filter for the FOLDER column. This filter is supposed to retrieve data from the database and present it in a dropdown checkbox within that column. The filtering should be based on the selected data. ...

Angular 7/8 - A guide to accessing URL parameters within the app component

Currently, I have implemented Single Sign-On feature on my application. However, for testing purposes, I need to extract values from the URL localhost:4200/?id=test&name=testing&<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...

What is the quickest way to send a message with just one press of the Enter key

Whenever I press "Enter Keyword," the message should be sent instead of going to the next line. ...

Accurately Showing Values of Observable Objects

Hey there, I'm diving deeper into Angular and working on my first project. I am fetching data from my database using a service method: getPost(postID: String) { this.postDocument = this.db.doc('posts/' + postID) return this.postDo ...

Ways to provide information to an rxjs observer

It appears that most people find observers to be a piece of cake, but I personally struggle with them. I am trying to set up an observable that can receive a number input after it has been created, triggered by pressing a button. However, all the examples ...

Navigating the coexistence of Angular 1.2 and Angular 2 for an incremental upgrade

After working on a large code base in Angular 1.2 with multiple custom directives, I decided to seek advice from experts before making any changes. While going through the Angular documentation, I was pleased to discover the UpgradeAdapter for incremental ...

Issue with Angular 6 auth guard causing logged-in users to remain on a blank page

I came across this answer and am tweaking it to work with my authentication system: Angular 6 AuthGuard However, I'm facing an issue where after successful authentication, instead of redirecting to the specified URL, the auth guard leads to a blank p ...

Changing the type of value in a React select onChange

<Select options={options} value={selectedBusinessList} isMulti placeholder="Select Business" onChange={(value: any) => setSelectedBusinessList(value)} onInputChange={query => { if ...

Error encountered in Angular testing when component fixture becomes undefined after test execution with subcomponents in version 4.0.0-beta.8

I'm facing a strange issue while testing my Angular code. Setting things up goes smoothly, but when I define subcomponents in the TestBed.configureTestingModule declaration, things start to break. The initial test within a describe block works fine, b ...

I need to show the value of A$ in a React form input, but ensure that only the numerical value is

I'm currently facing an issue where I want to show the currency symbol A$ in an input field. <form [formGroup]="incomeForm" *ngFor="let field of incomeFields"> <mat-form-field fxFlex> <input matInput [value]="incomeForm ...

Emphasize cells and headers when a cell's value deviates from its initial value

I implemented cell editing in my primeng table. Here is the code: <div class="card"> <p-table [value]="products" dataKey="id" [tableStyle]="{ 'min-width': '50rem' }"> <n ...

The visibility of the button is dependent on refreshing the page with the F5

I'm currently experiencing an issue with my code. The backoffice button is not showing up when I log in as an admin, unless I refresh the page by pressing F5. useEffect(() => { // Ensure window.FB and window.FB.XFBML are defined before calling ...

Utilizing React with Typescript to Implement useReducer with Action Interface Featuring Union Type Support

My current challenge involves creating a reducer using the useReducer hook. I have defined an interface named Action which includes a property that can hold either a string or a number: type Actions = 'update_foo' | 'update_bar'; inter ...

Troubleshooting issues with importing modules in TypeScript when implementing Redux reducers

Struggling to incorporate Redux with TypeScript and persist state data in local storage. My current code isn't saving the state properly, and as I am still new to TypeScript, I could really use some suggestions from experienced developers. Reducers i ...

Display a JSON file within an Angular application using HTML

I have a JSON (link to the JSON) that I want to display in an html file. JSON: { "recipes": { "FRYING": { "Anchovies": [ [ {"500": "thawing"} ], [ {"60": "nothing"} ] ], "Codfis ...

Bold Chutzpah: Delving into AngularJS Testing using Jasmine and TypeScript

Currently, I am utilizing Angular 1.4.9 in combination with Jasmine 2.2.0 and Chutzpah 4.2.0. My Angular code and unit tests are both written in TypeScript within Visual Studio 2015 Update 1. The issue I am facing mirrors that which was previously discuss ...

Every npm task results in an identical error, even the simple version check (npm -v). In contrast to previous inquiries, not one npm action is functioning

After installing Node version 12.13.0 on my Windows 10 system, I encountered an issue where all npm commands were throwing the following error: C:\Users\Jahangeer> npm -v evalmachine.<anonymous>:27 const { Math, Object } = prim ...

Trouble accessing files in the assets folder of Angular 2

I am encountering a 404 error when attempting to access a local file within my application. I am unable to display a PDF that is located in a sub-folder (pdf) within the assets folder. I am using CLI. <embed width="100%" height="100%" src="./assets/pdf ...