I have a mat-toolbar
with a login/logout button where the user of the website can login or out at all times. I have an authentication service which creates an Observable with user data and using *ngIf="!(authService.user$ | async)
for the login button. This isn't working though, unless I manually refresh the whole page. Why is this and what does one do about it? I thought the Observable would be a way that would actually work in these situations, but obviously I am missing something.
I have also tried subscribing to the Observable as user
in app.component.ts and using user
in the template, but this doesn't seem to help. I know there are several questions regarding user login with Observables, and questions about refresh, but they haven't given me an understanding of why this isn't working.
I should perhaps add that I am using an interface User
with property roles
, for role based authorisation, so it is not the same as firebase.User
.
Relevant parts of authentication.service.ts:
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
user$: Observable<User>;
viewAllUser: Boolean = false;
constructor(
private afAuth: AngularFireAuth,
private afs: AngularFirestore,
private router: Router) {
this.user$ = this.afAuth.authState.pipe(
switchMap(user => {
if (user) {
return this.afs.doc<User>(`Users/${user.uid}`).valueChanges()
} else {
return of(null)
}
}))
}
/* Sign up */
SignUp(email: string, password: string) {
this.afAuth.auth.createUserWithEmailAndPassword(email, password)
.then((result) => {
window.alert("You have been successfully registered!");
this.updateUserData(result.user)
//console.log(result.user);
}).catch((error) => {
window.alert(error.message);
//console.log(error.user);
});
}
/* Sign in */
SignIn(email: string, password: string) {
return this.afAuth.auth.signInWithEmailAndPassword(email, password)
.then((result) => {
window.alert("You have been successfully signed in!");
this.updateUserData(result.user);
//console.log(result.user);
}).catch((error) => {
window.alert(error.message);
//console.log(error.user);
});
}
/* Sign out */
SignOut() {
this.router.navigate(['user-main']);
this.afAuth.auth.signOut();
window.alert("You have been successfully signed out!");
}
private updateUserData(user) {
// Sets user data to firestore on login
const userRef: AngularFirestoreDocument<any> = this.afs.doc(`Users/${user.uid}`);
const data: User = {
uid: user.uid,
email: user.email,
roles: {
role1: true //default role
}
}
return userRef.set(data, { merge: true }) //Update in non-destructive way
}
}
app.component.html:
<body>
<mat-toolbar>
<span>
<button mat-menu-item *ngIf="!(authService.user$ | async) as user" routerLink="/user-main">Login</button>
<button mat-menu-item (click)="authService.SignOut()" routerLink="/user-main" *ngIf="authService.user$ | async">Logout</button>
{{user.email}} //for testing
</span>
<span>
<button mat-icon-button [matMenuTriggerFor]="appMenu">
<mat-icon>more_vert</mat-icon>
</button>
</span>
</mat-toolbar>
<mat-menu #appMenu="matMenu">
<!-- Only to be shown to logged in users: -->
<button mat-menu-item *ngIf="authService.user$ | async" routerLink="/user-main">User main</button>
<button mat-menu-item *ngIf="authService.user$ | async" routerLink="/page_x">Page X</button>
<button mat-menu-item *ngIf="authService.canViewData(authService.user$ | async)==true" routerLink="/secret_page_y">Secret page Y</button>
</mat-menu>
<!--This is where the routes are shown-->
<router-outlet></router-outlet>
</body>
app.component.ts:
import { Component } from '@angular/core';
import { AuthenticationService } from './shared/authentication.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
user;
constructor(public authService: AuthenticationService) {
this.authService.user$.subscribe(user => this.user = user);
}
}
You should use a BehaviorSubject
for the user and use it like :
authentication.service.ts:
private currentUserSubject = new BehaviorSubject<User>({} as User);
public currentUser = this.currentUserSubject.asObservable().pipe(distinctUntilChanged());
getCurrentUser(): User {
return this.currentUserSubject.value;
}
/* Sign up */
SignUp(email: string, password: string) {
this.afAuth.auth.createUserWithEmailAndPassword(email, password)
.then((result) => {
window.alert("You have been successfully registered!");
this.updateUserData(result.user);
//console.log(result.user);
}).catch((error) => {
window.alert(error.message);
//console.log(error.user);
});
}
/* Sign in */
SignIn(email: string, password: string) {
return this.afAuth.auth.signInWithEmailAndPassword(email, password)
.then((result) => {
window.alert("You have been successfully signed in!");
this.updateUserData(result.user);
//console.log(result.user);
}).catch((error) => {
window.alert(error.message);
//console.log(error.user);
});
}
private updateUserData(user) {
// Sets user data to firestore on login
const userRef: AngularFirestoreDocument<any> = this.afs.doc(`Users/${user.uid}`);
const data: User = {
uid: user.uid,
email: user.email,
roles: {
role1: true //default role
}
}
this.currentUserSubject.next(data); // --> here
return userRef.set(data, { merge: true }) //Update in non-destructive way
}
}
app.component.ts:
this.authService.currentUser.subscribe(user => this.user = user);
auth-guard.service.ts:
const user = this.authService.getCurrentUser();
if (user.id) {
return true;
} else {
return false;
}