htmlangulartypescriptangular-local-storagengoninit

Angular Redirection executes my method as well as NgOnInit. Why?


I am new with angular so bear with me. I am having issue with Angular Redirection.When I clear storage manually, code executes ngOnInit, prompts error,redirects to Login page (as expected), but when I try to do same thing using logout method my code executes Logout Method, ngOnInit and then redirect to login page. why it is executing ngOnInit of same page when I am redirecting to another page ? The code below shows logout method.

I tried making it globally, moving code to Constructor

this.localStorage.clear().subscribe(() => {
    console.log('Logout Method'); 
    alertify.success("Logout Successfull !!");  
    this.router.navigate(['/login']);
    }, () => {
      alertify.error("Storage error"); 
});

The code should just execute logout method instead of executing both logout and ngOnInit


Solution

  • It seems I did some mistake in my code

    <a href="main_nav#" (click)="logout()" >Logout</a>

    I was directing my URL in HREF to main_nav and then calling logout(). So after removing contents of HREF it worked for me.

    <a href="" (click)="logout()" target="_self">Logout</a>

    This worked for me ☻