Show template according to user status

Asked

Viewed 202 times

0

I am developing a system but I am having difficulties in the authentication part, or better, not necessarily in the authentication part, but rather in the part to show or not certain content according to the user status (logged in or not).

Basically, I am doing the control using ngIF, which calls a method that checks whether the user is logged in or not, if you call home, if you do not call login, so far so good, ta working without problem.

The problem is when the user logs in, when I refresh the page first shows the login screen to only then show the home of the site, and something relatively fast, shows the login and then the home, what I want and try to synchronize it, so I want to test user status and depending on the result show the home or login.

app.component.html

<div class="wrapper" *ngIf="isLoggedIn">
<cma-header></cma-header>
<cma-sidebar></cma-sidebar>
<router-outlet></router-outlet>
</div>

<div class="wrapper" *ngIf="!isLoggedIn">
<cma-login></cma-login>
</div>

app.componentts.

import { Component, OnInit } from '@angular/core';
import * as firebase from 'firebase';
import { AuthService } from './autenticacao/autenticacao.service';
import { Router } from '@angular/router';


@Component({
selector: 'cma-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {

public user$ = this.authService.user;
public isLoggedIn;

constructor (private authService: AuthService, private router: Router) {
authService.isAuthenticated().subscribe(
success => this.isLoggedIn = success,
  error => console.log(this.isLoggedIn)
);
}

ngOnInit() {
}

}
  • Take a look at the documentation of Route Guards -> https://angular.io/guide/router#Milestone-5-route-Guards

1 answer

0

Try to put the:

authService.isAuthenticated().subscribe(
success => this.isLoggedIn = success,
  error => console.log(this.isLoggedIn)
);

within the ngOnInit()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.