'Why does Angular not update the UI onInit?
I want to check if the user is logged in and display/hide the login button based on a boolean value. But for some reason, the button is always displayed. This is the app.component.ts:
@Component({
selector: 'ip-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
loggedIn: boolean = false;
constructor(
private translateService: TranslateService,
private authenticationService: AuthenticationService,
public dialog: MatDialog
) { }
ngOnInit() {
this.authenticationService.checkLogin();
this.authenticationService.loggedIn.subscribe(loggedIn => this.loggedIn = loggedIn);
}
}
This is app.component.html:
<mat-toolbar color="primary">
<app-navigation></app-navigation>
<button *ngIf="!loggedIn" mat-raised-button (click)="openLoginDialog()">{{'authentication.login' | translate}}</button>
</mat-toolbar>
<router-outlet></router-outlet>
This is the authentication.service.ts:
@Injectable()
export class AuthenticationService {
public loggedIn: Subject<boolean> = new BehaviorSubject<boolean>(false);
constructor(private httpClient: HttpClient) {
}
checkLogin(): void {
const accessToken = localStorage.getItem('access_token');
const headers = new HttpHeaders({'access_token': accessToken});
this.httpClient.post(url, null, {headers}).subscribe(result => this.loggedIn.next(true));
}
}
The service is part of the authentication.module.ts which is imported to app.component.ts. I already tried marking it as singleton with providedIn: 'root', but that didn't work. The funny thing is, that if I click on the login button, it disappears, but I want to make it disappear on the loading of the page.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
