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

Angular 2: Emptying input field value on click event

I am experiencing an issue with resetting my input values. I have a search bar with filter functions. When I enter a value, it displays a list below and I want to add a function to these links. When I click on one of them, it takes me to another component ...

Issue encountered while executing jest tests - unable to read runtime.json file

I've written multiple unit tests, and they all seem to pass except for one specific spec file that is causing the following error: Test suite failed to run The configuration file /Users/dfaizulaev/Documents/projectname/config/runtime.json cannot be r ...

Change a TypeScript alias within the @types namespace

While using Typescript 3, I encountered a situation where I needed to modify a type alias from the @types/json-schema definition provided by DefinitelyTyped. The issue arose when I wanted to incorporate a custom schema type into my code. Since this custom ...

The Validator in Angular Formbuilder must have a specific character requirement

Can someone help me with a regex validator pattern in Angular Formbuilder to ensure that the field CityStateZip contains at least one comma as a special character? this.editAddressForm = this.formBuilder.group({ 'CustomerName': [null, ...

Using {children} in NextJS & Typescript for layout components

I am looking to develop a component for my primary admin interface which will act as a wrapper for the individual screens. Here is the JavaScript code I have: import Header from '../Header' function TopNavbarLayout({ children }) { return ...

Tips on how to effectively simulate a custom asynchronous React hook that incorporates the useRef() function in jest and react-testing-library for retrieving result.current in a Typescript

I am looking for guidance on testing a custom hook that includes a reference and how to effectively mock the useRef() function. Can anyone provide insight on this? const useCustomHook = ( ref: () => React.RefObject<Iref> ): { initializedRef: ...

"Adjusting the size of a circle to zero in a D3 SVG using Angular 2

Trying to create a basic line graph using d3 in Angular 2 typescript. Below is the code snippet: import { Component, ViewChild, ElementRef, Input, OnInit } from '@angular/core'; import * as d3 from 'd3'; @Component({ selector: 'm ...

What does the 'key' parameter represent in the s3.put_object() function?

Currently, I'm utilizing Boto in my project to upload artifacts to an s3 bucket. However, I am uncertain about the usage of the Key parameter within the put_object() method: client.put_object( Body=open(artefact, 'rb'), Bucket=buc ...

Utilize the TypeScript Compiler API to extract the Type Alias Declaration Node from a Type Reference Node

Currently, I am utilizing ts-morph library which makes use of the TS Compiler API. Here is an example of my code: export type Foo = string export const foo: Foo = 'bar' Whenever I try to find the type for the export of foo, it returns string. H ...

mongodb is experiencing issues with the findOneAndUpdate operation

Below is the code snippet for updating the database. let profileUrl = 'example' UserSchemaModel.findOneAndUpdate({_id:userId}, {$set: {profileUrl:profileUrl} }, {new:true}) .then((updatedUser:UserModel) => { console.log(updatedUser.profil ...

Rendering illuminated component with continuous asynchronous updates

My task involves displaying a list of items using lit components. Each item in the list consists of a known name and an asynchronously fetched value. Situation Overview: A generic component named simple-list is required to render any pairs of name and va ...

Passing a value from an HTML template to a method within an Angular 4 component

Encountering an issue with Angular 4. HTML template markup includes a button: <td><a class="btn btn-danger" (click)="delete()"><i class="fa fa-trash"></i></a></td> Data is assigned to each td from a *ngFor, like {{ da ...

"Discover the seamless process of uploading images in Angular 7 directly from the backend

I'm facing an issue where I can upload images using Postman, but it's not working for me in Angular. Can someone please provide a solution? Error: Cannot read originalname of undefined in Node.js, but it works with Postman! //backend var exp ...

Locate and embed within a sophisticated JSON structure

I have an object structured as follows: interface Employee { id: number; name: string; parentid: number; level: string; children?: Employee[]; } const Data: Employee[] = [ { id:1, name: 'name1', parentid:0, level: 'L1', children: [ ...

What is the mechanism behind Typescript interface scope? How can interfaces be defined globally in Typescript?

I'm diving into the world of Typescript and Deno, but I'm struggling to understand how interfaces scopes work. Here's the structure of my application: The first layer (App.ts) contains the core logic of my application. This layer can refer ...

Validating Form Controls with Dynamic Names in Angular 5

Initially, I believed this task would be straightforward. The following snippet of HTML is functioning as anticipated: <label class="mb-0 form-label"> Doc Part </label> <input type="number" name="DocPart" #DocPart="ngModel" class="form- ...

What is the best way to switch the CSS class of a single element with a click in Angular 2

When I receive data from an API, I am showcasing specific items for female and male age groups on a webpage using the code snippet below: <ng-container *ngFor="let event of day.availableEvents"> {{ event.name }} <br> <n ...

Angular2 fills up the table with data for a particular row

I have a specific requirement where I need to display only some columns of a table within a div. When I click on 'See' for a particular row, I want to reveal the remaining columns of that table (currently it reveals all rows by default). https:/ ...

Tips on using class-validator @isArray to handle cases where only a single item is received from a query parameter

Currently, I am attempting to validate a request using class-validator to check if it is an array. The inputs are sourced from query parameters like this: /api/items?someTypes=this This is what my request dto resembles: (...) @IsArray() @IsEn ...

What causes TypeScript to struggle with inferring types in recursive functions?

Here is a code snippet for calculating the sum: //Function to calculate the sum of an array of numbers let sum = ([head, ...tail]: number[]) => head ? head + sum(tail) : 0 let result: string = sum([1, 2, 3]); alert(result); Can anyone explain why ...