I'm lost in the madness of observables, promises and state. I need help to figure this out.
I'm trying to implement register/sign-in/sign-up functionality in my angular 2 application with the Angularfire2 module. I'm starting with the login functionality. I got the basics working. I can login and redirect to a new page. So far so good. In my template I'm checking if a user is logged in or not. And here starts the trouble. I having an hard time checking if the current user is logged in or not.
Login.components.ts
import { Component, OnInit } from '@angular/core';
import {Validators, FormGroup, FormBuilder } from '@angular/forms';
import { AuthService } from '../auth.service';
import {Router} from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
form: FormGroup;
error = false;
errorMessage = '';
constructor(private fb:FormBuilder, private authService:AuthService, private router:Router) {}
ngOnInit() {
this.form = this.fb.group({
email: ['', Validators.required],
password: ['', Validators.required]
});
}
onLogin() {
this.authService.loginUser(this.form.value.email, this.form.value.password)
.subscribe(
() => this.router.navigate(['/'])
)
}
}
Auth.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import {FirebaseAuth} from 'angularfire2/index';
import {Observable, Subject} from 'rxjs/Rx';
@Injectable()
export class AuthService {
constructor(private auth: FirebaseAuth, private router:Router) { }
loginUser(email, password):Observable<any> {
return this.fromFirebaseAuthPromise(this.auth.login({email,password}));
}
logout() {
this.auth.logout();
this.router.navigate(['/']);
}
fromFirebaseAuthPromise(promise):Observable<any> {
const subject = new Subject<any>();
promise
.then(res => {
subject.next(res);
subject.complete();
},
err => {
subject.error(err);
subject.complete();
});
return subject.asObservable();
}
isAuthenticated(): Observable<any> {
const state = new Subject<any>();
this.auth.subscribe( (user) => {
if (user) {
var uid = user.uid;
console.log('the user id:' + uid)
state.next(true)
} else {
console.log("no user")
state.next(false)
}
})
return state.asObservable();
}
}
home.component.ts
import { Component, OnInit } from '@angular/core';
import { AuthService } from './auth/auth.service';
import { AuthInfo } from './auth/auth-info';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
isAuthenticated = false;
constructor(private authService:AuthService) {
this.authService.isAuthenticated().subscribe(
authStatus => this.isAuthenticated = authStatus
);
console.log('isAuthenticated:' + this.isAuthenticated);
}
isAuth() {
return this.isAuthenticated;
}
onLogout() {
this.authService.logout();
}
ngOnInit() {
}
}
home.component.html
<h2>
Please login or register to use the app
</h2>
<a [routerLink]="['/login']" *ngIf="!isAuth()">Login here</a>
<a [routerLink]="['/register']" *ngIf="!isAuth()">Register here</a>
<a *ngIf="isAuth()" (click)="onLogout()" style="cursor: pointer;">Logout</a>
When I look at my console when loginning in I see the following results.
{
the user: id:qqsrQHB0SyeIQTbri6sYEyTTE9r2
isAuthenticated: false
}
So I guess to login must be successful right? But when I check to see if authentication is true seems to fail. The *ngIf="!isAuth()" in the HomeComponent
does not work, only if I do a hard refresh in the browser.
After a hard refresh I still see in the console:
{
the user: id:qqsrQHB0SyeIQTbri6sYEyTTE9r2
isAuthenticated: false
}
You have complicated so much, this how your code should be:
Auth.service
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { FirebaseAuth } from 'angularfire2/index';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class AuthService {
constructor(private auth: FirebaseAuth, private router:Router) { }
loginUser(email, password) {
return this.auth.login({email,password}) //angularfire returns a promise
}
loginUserObservable(email,password){ //but if still want to use an observable
return Observable.fromPromise(<Promise<any>> this.auth.login({email,password})) // we need to cast the Promise because for some reason Angularfire returns firebase.Promise
}
logout() {
this.auth.logout();
this.router.navigate(['/']);
}
isAuthenticated(): Observable<any> {
return this.auth; //auth is already an observable
}
}
home.component.ts:
import { Component, OnDestroy, OnInit } from '@angular/core';
import { AuthService } from './auth/auth.service';
import { AuthInfo } from './auth/auth-info';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit, OnDestroy {
private sub: Subscription;
constructor(private authService:AuthService) { }
ngOnInit() {
this.sub = this.authService.isAuthenticated().subscribe(authResp =>
console.log('isAuthenticated: ', authResp);
);
}
ngOnDestroy() {
this.sub.unsubscribe();
}
isAuth() {
return this.authService.isAuthenticated();
}
onLogout() {
this.authService.logout();
}
}
home.component.html
<h2>
Please login or register to use the app
</h2>
<a [routerLink]="['/login']" *ngIf="!(isAuth() | async)">Login here</a>
<a [routerLink]="['/register']" *ngIf="!(authService.isAuthenticated() | async)">Register here</a>
<!--you can either use !(isAuth() | async) or !(authService.isAuthenticated() | async) it's up to your religion -->
<a *ngIf="isAuth() | async" (click)="onLogout()" style="cursor: pointer;">Logout</a>
I advise you to read this simple guide
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With