Encountering an error while compiling the Angular 8 app: "expected ':' but got error TS1005"

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",
    ...
   }
}

Answer №1

Give this a shot

this.email = user ? user.email ? user.email :"Email not available" : "User information missing";

or

if(user != null && user!= undefined)
{
  if(user.email != null && user.email != undefined)
   {
    this.email = user.email;
   }
}

or

if( (user != null && user!= undefined) && (user.email != null && user.email != undefined))
{
    this.email = user.email;  
}

Answer №2

In my understanding, the use of the ".?" expression is to check if the value of "user" is null or undefined. If it is, then it will return undefined. Therefore, it seems that in your scenario, the use of this expression may be unnecessary. If the user value is meant to be null or undefined, you will still receive undefined even without using the ".?" expression.

For more information, you can visit: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Capturing a center mouse click event in a directive for Angular 6

I created a unique custom directive where I aim to capture middle mouse button click events. Initially, I thought it would be a straightforward process by setting the normal click event and working from there. However, I noticed that it only triggers when ...

Could the autofill feature in Chrome be turned off specifically for Angular form fields?

Even after attempting to prevent autofill with autocomplete=false and autocomplete=off, the Chrome autofill data persists. Is there a method to disable autofill in Angular forms specifically? Would greatly appreciate any recommendations. Thank you. ...

The GET API is functioning properly on Google Chrome but is experiencing issues on Internet Explorer 11

Upon launching my application, I encountered an issue with the v1/validsColumns endpoint call. It seems to be functioning properly in Chrome, but I am getting a 400 error in IE11. In IE v1/validCopyColumns?category=RFQ&columns=["ACTION_STATUS","ACTIO ...

How to Utilize Class Members in a Callback Function in Angular 12 with Capacitor Version 3

When I click the "Device Hardware Back Button" using Capacitor 3.0, I'm trying to navigate to the parent component with the code below. The device back button is working correctly, but I'm facing an issue where I can't access class members i ...

Leveraging Angular for Remote Configuration Management

How is everything going with you? I'm attempting to retrieve a configuration that I previously set up in Firebase's remote config using my Angular 15 application. The specific configuration is called "AllowedUsers." Here is the image of th ...

An operator in rxjs that transforms an Observable of lists containing type X into an Observable of type X

Currently, I am facing a challenge while dealing with an API that is not very user-friendly using Angular HTTP and rxjs. My goal is to retrieve an Observable<List<Object>> from my service. Here's a snippet of the JSON output obtained from ...

`Can you bind ngModel values to make select options searchable?`

Is there a way to connect ngModel values with select-searchable options in Ionic so that default values from localStorage are displayed? <ion-col col-6> <select-searchable okText="Select" cancelText="Cancel" cla ...

Input box in Angular matDatepicker fails when typing due to locale settings

When using a datepicker like this: <mat-form-field> <input matInput [matDatepicker]="picker" placeholder="Choose a date"> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker> ...

Having trouble triggering a dot MVC controller action method from an Angular service

Encountering the following Error: CORS policy block: Preflight request response access control check fails with HTTP ok status missing. Note: The ajax call successfully triggers the action method in other web applications, but an error is raised when usin ...

Upon clicking the button, the Angular Mat-Table with Reactive Forms fails to display any data, instead adding a blank row accompanied by errors

When the AddRow_click() function is executed, I populate the insuranceFormArray and assign its values to the datasource. However, after adding an entry, an empty row appears in the table, and error messages are displayed in the console. Only a subset of th ...

A practical guide to effectively mocking named exports in Jest using Typescript

Attempting to Jest mock the UserService. Here is a snippet of the service: // UserService.ts export const create = async body => { ... save data to database ... } export const getById = async id => { ... retrieve user from database ... } The ...

Choosing the correct key and handling parsing errors

As I work on converting a class component to TypeScript, I encountered an error while trying to implement one of my onChange methods. The error message stated: "Argument of type '{ [x: number]: any; }' is not assignable to parameter of type &ap ...

What are the steps to set up NextJS 12.2 with SWC, Jest, Eslint, and Typescript for optimal configuration?

Having trouble resolving an error with Next/Babel in Jest files while using VSCode. Any suggestions on how to fix this? I am currently working with NextJS and SWC, and I have "extends": "next" set in my .eslintrc file. Error message: Parsing error - Can ...

Adjust the button sizes in Ngprime

I am trying to customize my primeng buttons because they appear too large for my project. I found in the documentation that I can make them smaller by using: <p-button label="Small" icon="pi pi-check" styleClass="p-button-sm&quo ...

The function you are trying to call is not callable. The type 'Promise<void>' does not have any call signatures. This issue is related to Mongodb and Nodejs

Currently, I am attempting to establish a connection between MongoDB and Node (ts). However, during the connection process, I encountered an error stating: "This expression is not callable. Type 'Promise<void>' has no call signatures" da ...

In Typescript, we can streamline this code by assigning a default value of `true` to `this.active` if `data.active

I am curious if there is a better way to write the statement mentioned in the title. Could it be improved with this.active = data.active || true? ...

How to use attributes in Angular 2 when initializing a class constructor

Is there a way to transfer attributes from a parent component to the constructor of their child components in Angular 2? The process is halfway solved, with attributes being successfully passed to the view. /client/app.ts import {Component, View, bootst ...

After updating to version 13 of Angular and Angular Material, the mat-contenteditable feature has ceased functioning

Encountered errors with mat-contenteditable after updating Angular from version 12 to 13 Error: /node_modules/mat-contenteditable/lib/mat-ckeditor.directive.d.ts:9:22 - error TS2420: Class 'MatCkeditorDirective' incorrectly implements interface & ...

Customizing the output format of Ng Date Picker beyond the standard ISO-8601

Just to clarify, I'm talking about a specific DatePicker component that can be found at the following link: Although the DatePicker interface is user-friendly and visually appealing, I'm facing an issue with the way it outputs values. While ther ...

"Enhancing global accessibility through i18n strategies and evolving language usage

I am looking to update the terminology used in my Angular application. Essentially, I need i18n functionality, but I am not interested in changing the language or implementing localization. The app will remain in English, and I simply want to modify certa ...