After navigating to another route, the ngOnInit() function continues to run for a period of time

In my current project, I am working on integrating an Angular 5 application. One of the components in this application is called Solution, which receives data from another component.

Everything was functioning smoothly until I encountered a problem when reloading the browser page. Upon pressing the Reload button, no data was being sent to the component. To address this issue, I implemented an if statement to check if the received data is undefined. If it is, the user is redirected to the home page.

Although this solution worked and successfully redirected users to the home page, there was a delay in the navigation process. Meanwhile, the remaining parts of the Solution component continued to load, causing all variables to become undefined. As a result, any count function or toFixed() function used in the HTML would trigger errors in the console.

To overcome this challenge, I developed a temporary workaround by moving the remaining logic of the ngOnIt method to the else statement within the if condition mentioned earlier. Additionally, I utilized the *ngIf directive in the HTML code to verify the presence of incoming data from the service. While this approach resolved the immediate issue, it is not considered the optimal solution.

 export class SolutionComponent implements OnInit {
    res;
    solutionData = new SolutionData()
    constructor(private SolutionService: GetSolutionService,
        private http: Http,
        private router: Router) { }

    ngOnInit() {
        this.res = this.SolutionService.response;
        if (this.res === undefined) {    
            this.router.navigate(['Home']); 
        } else {
            this.solutionData.Temp = this.res.json()['Temp'];
            this.solutionData.Press = this.res.json()['Press'];
         }
    }

For example, in the HTML file:

<div *ngIf="res!==undefined">
    <div> Temp Equals {{res.Temp.toFixed(2)}} </div>
    <div> Press Equals {{res.Press.toFixed(2)}} </div>
</div>

Answer №1

It's important to note that the issue is not related to ngOninit. The problem lies in your ngIf condition itself; it should only check if the value exists and you should also utilize the safe navigation operator to ensure that variables have values.

<div *ngIf="res">
       <div> Temperature: {{res?.Temp?.toFixed(2)}} </div>
       <div> Pressure: {{res?.Press?.toFixed(2)}} </div>
</div>

Answer №2

To prevent any issues, consider implementing an *ngIf condition on your solution component. By doing so, the component will only be loaded if the condition is met, reducing the likelihood of errors. For example:

  <solution-component *ngIf='data'
[inputData]= 'data'>
</solution-component>

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

Changing the key of a JavaScript request object into a string variable

Just starting out with programming. The API post call requires an object variable (derived from a variable) to be passed as a string like this: "option": { "235": “30” }, { "238": “32” } In my Angular 6 code: ...

Is it possible to locate a specific entry by searching within an array data type in Firebase using Angular 6?

I am facing a challenge with firebase collection as I have an array type key that stores numerous ids. I need to find the value by searching for one specific id within that array type value. Is there a where clause query available in firebase for Angular 6 ...

Strategies for transferring ngModel data from child components to parent components (child to parent to grandparent)

I am currently working on multiple parent components that utilize template-driven forms: user-data.components.ts admin-data.components.ts customer-data.components.ts Each of these parent components have form elements that are child components utilizing NG ...

Issue: The specified selector "app-redirect" does not correspond to any elements. I am currently in the process of transitioning to MSAL v2 and need to retrieve a refresh token

[Seeking Console Error Resolution import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { SharedModule } from './shared/shared.module' import { AppRoutingModule } from ...

How to efficiently retrieve parent content from a child component

parent.html <ion-content class="project"> <ion-grid> <ion-row class="details"> <project [data]="data"></project>// this child component </ion-row> </ion-grid> </ion-content> project.ht ...

managing commitments in TypeScript

Is there a way to convert a promise into a string, or is there another method for handling this result? I am encountering an error stating "You cannot use an argument of type 'Promise' for a parameter of type 'string'." const pokemonIma ...

How to handle form-data in NestJS Guards?

I've been trying to access form-data in my NestJS Guards, but I'm experiencing some difficulties. Despite following the tutorial provided here, I am unable to see the request body for my form-data input within the Guard itself. However, once I ac ...

TypeScript abstract class generics: `Class<?>` type

When working with TypeScript, I often utilize a Java-like type called Class: interface Class<T = void> { new(...args: any[]): T; } Unfortunately, this type doesn't seem to be compatible with abstract classes: abstract class Bar {} class ...

What is the best placement for "platform: 'node'" within an Angular 17 application that is hosted on node 20?

Summary: I am struggling to locate the file where platform: 'node' should be added in order for my Angular app to access modules that are no longer bundled with WebPack 5 but are bundled with node. Could someone please provide guidance on where ...

Tips for dealing with strong reference cycles in TypeScript?

I have created a tree-like structure in my implementation, consisting of parent and child objects. The parents contain a list of children while the children have references to their parents, facilitating easy navigation through the tree. I am now contempla ...

Angular 11 is giving an error message stating that the 'async' pipe cannot be located

Struggling to fetch data using Angular 11 as an observable? Issues arise when using async or JSON pipe in a lazy loaded component/module, resulting in errors displayed in the console. The module: import { NgModule } from '@angular/core'; import ...

EventEmitter is failing to refresh the properties bound with [(ngModel)]

I am currently working with the forms module and Google Maps to update the geocode based on the search box provided on the map. The map is a separate component that emits the Geocode using the function geoCodeChange(). This event is handled by another func ...

Is there a way to efficiently update the template within the *ngFor directive when working with an array of objects in Angular 2/

My Json Object is structured as follows: var obj = { "TimSays":"I can Walk", "RyanSays":"I can sing", "MaxSays":"I can dance", "SuperSays":"I can do it all" } To iterate through this object in the template, I am using a pipe helper due to ...

Filtering an array does not restrict the type of elements within it

I am facing a scenario where I have an interface containing two optional properties: interface A { one?: string; two?: string; } I want to pass these properties inside an array to a component that specifically requires string[] export const MyComponen ...

Implement Angular7 server side rendering on Azure App Service and launch the application

My Angular7 app is built with ServerSide Rendering using angular universal and it's wrapped inside a .Net Core application. However, I'm facing issues when attempting to deploy it to Azure App Service. During the publish process in Visual Studio ...

What steps should I take to address this issue using IONIC and TypeScript?

Running into an issue with my TypeScript code for an Ionic project. I'm attempting to pass the value of the variable (this.currentroom) from the getCurrentRoom() function to another function (getUser()) but it's not working. Here's my chat s ...

Tips for displaying a div element alongside a button within a reactJS table

How can I position a div element next to a button in a ReactJS table? I have a table component where I want to display some options in a small window that closes when clicked outside. Options : https://i.sstatic.net/sT8Oi.png Action button in the table ...

Steps for modifying the value of a field within an Angular formGroup

Is there a way to update the value of the "send_diagnostic_data" field in a separate function? private generateForm(): void { this.messageForm = new FormGroup({ message: new FormControl(''), date: new FormControl(new Date()), messag ...

The access token generated by the Angular Keycloak adapter for Spring Boot backend authorization is not valid

The access tokens generated by Angular's keycloak adapter are invalid for communicating with a Spring Boot backend application secured by the same Keycloak realm. The localhost addresses were replaced with example.com to avoid issues with spam filters ...

Error in Angular 2 component when loading background images using relative URLs from an external CSS skin

In my angular2 component, I am utilizing a third-party JavaScript library. The skin CSS of the component attempts to load images using relative URL paths. Since I am following a component-based architecture, I prefer to have all component dependencies enca ...