Reputation: 23
I am new to both. My thought process is as follows. When I login in with Angular to my Firebase backend I send a response to the console if it succeeds. In this response I can see all the keys that a firebase user has. What I want to do is to link these to/in a user model in my front-end so I can access it easily when showing a user profile page or something else. (I don't know if this is the correct thought process too. Nudge me in the right way if you know a better solution)
auth.service.ts
constructor(
private angularFireAuth: AngularFireAuth,
) {
this.userData = angularFireAuth.authState;
}
signIn(email: string, password: string) {
return this.angularFireAuth.auth.signInWithEmailAndPassword(email, password);
}
login.component.ts
signIn(email: string, password: string) {
this.spinnerButtonOptions.active = true;
email = this.loginForm.value.email;
password = this.loginForm.value.password;
this.auth.signIn(email, password).then(
res => {
console.log('signed in ', res);
this.router.navigate(['/dashboard']);
}
).catch(
error => {
console.log('something went wrong ', error);
this.formError = true;
this.spinnerButtonOptions.active = false;
}
);
}
How would I got on to do this? I've searched everywhere and can't find any solution. Is this actually the correct way? If there is a better way please let me know!
Upvotes: 2
Views: 289
Reputation: 6858
You can use your auth service to store the data returned from the Firebase backend. Or else you can store it in a shared service where it's been available throughout the all components and modules.
In your auth service :
@Injectable()
export class AuthService{
public usermodel:any;
constructor(private angularFireAuth: AngularFireAuth) {
this.userData = angularFireAuth.authState;
}
signIn(email: string, password: string) {
return this.angularFireAuth.auth.signInWithEmailAndPassword(email, password);
}
setLoggedInUserData(userDetails: any) {
this.usermodel = userDetails;
}
getLoggedInUserData() {
return this.usermodel;
}
}
In you login component.ts :
signIn(email: string, password: string) {
this.spinnerButtonOptions.active = true;
email = this.loginForm.value.email;
password = this.loginForm.value.password;
this.auth.signIn(email, password).then(
res => {
this.authService.setLoggedInUserData(res);
this.router.navigate(['/dashboard']);
}
).catch(
error => {
console.log('something went wrong ', error);
this.formError = true;
this.spinnerButtonOptions.active = false;
}
);
}
In other components where you need to use the use details inject the auth.service.ts and use the getLoggedInUserData()
method fetch the logged in users details.
There are several other ways of doing this too. One option is to use the ngrx store implementation. Other ways is to use global data service at the root level of your angular app to store the user details.
Upvotes: 1