Tools I'm Utilizing
- Angular 5
- AngularFire5
- Firebase & Firestore
Objective
I am working on developing a straightforward authentication/login and registration system. While I have already created one, I am facing some challenges and seeking the best approach to set up authentication.
Current Progress
auth.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { AngularFireAuth } from 'angularfire2/auth';
@Injectable()
export class AuthService {
authState: any = null;
email = '';
username = '';
password = '';
errorMessage = '';
error: {name: string, message: string} = {name: '', message: ''};
constructor(private afAuth: AngularFireAuth, private router: Router) {
this.afAuth.authState.subscribe((auth) => {
this.authState = auth
});
}
get isUserEmailLoggedIn(): boolean {
if (this.authState !== null) {
return true
} else {
return false
}
}
get currentUser(): any {
return (this.authState !== null) ? this.authState : null;
}
get currentUserId(): string {
return (this.authState !== null) ? this.authState.uid : ''
}
// Other methods omitted for brevity
}
link.service.ts
import { Injectable, OnInit } from '@angular/core';
import { AuthService } from './auth.service';
import { AngularFirestore, AngularFirestoreDocument, AngularFirestoreCollection } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
export interface Link { uid: string; url: string; shortURL: string; clicks: number }
@Injectable()
export class LinkService implements OnInit {
url: string;
shortURL: string;
showAlert: boolean;
links: Observable<any>;
constructor(public authService: AuthService, private afs: AngularFirestore) {
this.links = afs.collection('Links').valueChanges();
}
// Methods and logic removed for simplicity
}
Challenge Faced
In my implementation, I encountered an issue where I am unable to retrieve the currentUserID in the link.service.ts file as it returns undefined. However, the
this.authService.isUserEmailLoggedIn
function within the addLink() method works correctly. It's perplexing why it doesn't provide the correct value elsewhere.