Search code examples
angularauthenticationangular-routing

Angular 7 component redirection without routing


With my current Angular 7 and Firebase setup I have the following situation:

I have the main app component which shows the member area if the user is logged in or otherwise the public area. Everything is working fine, but there is a 1-2 second delay until the correct component shows after signing out or in. I don't want to use routing btw. because I want to show everything with the same URL.

Do you have an idea how I can reduce the delay and is this a good practice of doing authentication anyway? I appreciate all your help!

app.component.html

<div *ngIf="authService.isAuthorized(); else showLogin">
  <app-member></app-member>
</div>
<ng-template #showLogin>
  <app-public></app-public>
</ng-template>
<router-outlet></router-outlet>

And then here the components for the member area and public area:

member.component.html:

<button nz-button [nzSize]="size" nzType="primary (click)="authService.logout()">Logout</button>

public.component.html:

<button nz-button [nzSize]="size" nzType="primary" (click)="authService.login()">Login</button>

Solution

  • With your initial approach, I suggest you to use a variable as observable that defines whether the user is authorized in or not, better than call the function authService.isAuthorized(). You can do this defining an observable property in your authservice:

    AuthService.ts

    isAuthorized() {
        ...
        this.isAuthorized.next(true);
    }
    isAuthorized$ = this.isAuthorized.asObservable();
    

    In this way, the property will be automatically updated in your main template by doing something like this:

    app.component.ts

    authService.isAuthorized$.subscribe((response) => {
        this.isAuthorized = response;
    });
    

    Then you can use on your main template:

    app.component.html

    <div *ngIf="isAuthorized" ; else showLogin">

    And to handle the possible wait, as AJT_82 has already commented, it would be best to put a spinner until the call has been made.