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>