As I work on developing an Angular 8 application through a tutorial, I find myself facing a challenge in my header component. Specifically, I am looking to display the email address of the currently logged-in user within this component. The code snippet from my auth.service.ts is detailed below:
import { Injectable } from "@angular/core";
import { AngularFireAuth } from "@angular/fire/auth";
@Injectable({
providedIn: "root",
})
export class AuthService {
constructor(private auth: AngularFireAuth) {}
signUp(email: string, password: string) {
return this.auth.auth.createUserWithEmailAndPassword(email, password);
}
signIn(email: string, password: string) {
return this.auth.auth.signInWithEmailAndPassword(email, password);
}
getUser() {
return this.auth.authState;
}
signOut() {
return this.auth.auth.signOut();
}
}
In addition to that, here is a glimpse of my header.component.ts file:
import { Component, OnInit } from "@angular/core";
import { AuthService } from "src/app/services/auth.service";
import { ToastrService } from "ngx-toastr";
import { Router } from "@angular/router";
@Component({
selector: "app-header",
templateUrl: "./header.component.html",
styleUrls: ["./header.component.css"],
})
export class HeaderComponent implements OnInit {
email:string = null;
constructor(
private auth: AuthService,
private router: Router,
private toastr: ToastrService
) {
auth.getUser().subscribe((user)=>{
console.log("User is:",user);
this.email = user?.email;
})
}
ngOnInit() {}
async handSignOut(){
try {
await this.auth.signOut();
this.router.navigateByUrl("/signin");
this.toastr.info("Logout success");
this.email = null;
} catch (error) {
this.toastr.error("Problem in Signout");
}
}
}
After compiling this code, it throws an error stating:
ERROR in src/app/layout/header/header.component.ts:20:25 - error TS1109: Expression expected.
20 this.email = user?.email;
~
src/app/layout/header/header.component.ts:20:31 - error TS1005: ':' expected.
20 this.email = user?.email;
~
Upon removing the "?" from the line causing the issue (this.email = user?.email;), the compilation goes through successfully. How do I go about resolving this problem?
Here's an overview of my package.json :
{
"name": "travelgram",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "~8.2.7",
"@angular/common": "~8.2.7",
"@angular/compiler": "~8.2.7",
"@angular/core": "~8.2.7",
"@angular/fire": "^5.4.2",
"@angular/forms": "~8.2.7",
"@angular/platform-browser": "~8.2.7",
"@angular/platform-browser-dynamic": "~8.2.7",
"@angular/router": "~8.2.7",
...
}
}