Reputation: 23
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>
Upvotes: 2
Views: 9730
Reputation: 435
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.
Upvotes: 0
Reputation: 435
I do not know how to do it without routing. Why do not you want to use it? It would be that simple: Using Angular's canActivate class on your app-routing.module.ts file.
For this, you will need to implement an authentication service that checks whether the user is loged in or not.
Example:
const routes: Routes = [
{
path: '',
component: MemberComponent,
canActivate: [YourAuthGuard],
},
{
path: 'public',
component: PublicComponent
}
];
@NgModule({
imports: [...],
exports: [...],
providers: [ YourAuthGuard ]
})
export class AppRoutingModule { }
Then you can put redirects from one component to another with the navigate () method of the Angular class Router.
Hope this can help you.
Upvotes: 2