Is there a syntax issue in your Angular/Typescript code?

I am currently developing a login system using Angular and Firestore, and here is the code I have written:

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

import * as firebase from 'firebase/app';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFirestore, AngularFirestoreDocument } from 'angularfire2/firestore';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/switchMap';


interface User {
  uid: string;
  email: string;
  photoURL?: string;
  displayName?: string;
  favouriteColor?: string;
}

@Injectable()
export class AuthService {

  user: Observable<User>;

  constructor(private afAuth: AngularFireAuth,
              private afs: AngularFirestore,
              private router: Router) {
                this.user = this.afAuth.authState
                  .switchMap(user => {
                    if (user) {
                      return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
                    } else {
                      return Observable.of(null);
                    }
                  });
               }

}

googleLogin(){
  const provider = new firebase.auth.GoogleAuthProvider();
  return this.oAuthLogin(provider);
}


private oAuthLogin(provider){
  return this.afAuth.auth.signInWithPopup(provider)
    .then((credential) => {
      this.updateUserData(credential.user);
    });
}

private updateUserData(user){
  const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.id}`);

  const data: User = {
    uid: user.uid,
    email: user.email,
    displayName: user.displayName,
    photoURL: user.photoURL
  };

  return userRef.set(data);
}

However, when checking my console log, it indicates that I am missing semicolons. I'm not exactly sure why:

ERROR in src/app/core/auth.service.ts(40,14): error TS1005: ';' expected.
src/app/core/auth.service.ts(46,1): error TS1128: Declaration or statement expected.
src/app/core/auth.service.ts(46,29): error TS1005: ';' expected.
src/app/core/auth.service.ts(53,1): error TS1128: Declaration or statement expected.
src/app/core/auth.service.ts(53,29): error TS1005: ';' expected.

Additionally, I encountered this error:

ERROR in ./src/app/core/auth.service.ts
Module parse failed: 'return' outside of function (48:4)
You may need an appropriate loader to handle this file type.
| {
|     var provider = new firebase.auth.GoogleAuthProvider();
|     return this.oAuthLogin(provider);
| }
| oAuthLogin(provider);

I am confused about what TypeScript is trying to communicate. For instance, TypeScript suggests adding a semicolon at line 40 where the googleLogin() function is defined, which seems odd to me.

If anyone can help identify the spelling mistake or error, I would greatly appreciate it. I've spent over an hour troubleshooting this issue and haven't been able to pinpoint the exact problem.

Thank you in advance.

Answer №1

Check out the updated code below:

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

import * as firebase from 'firebase/app';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFirestore, AngularFirestoreDocument } from 'angularfire2/firestore';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/switchMap';


interface User {
  uid: string;
  email: string;
  photoURL?: string;
  displayName?: string;
  favouriteColor?: string;
}

@Injectable()
export class AuthService {

  user: Observable<User>;

  constructor(private afAuth: AngularFireAuth,
              private afs: AngularFirestore,
              private router: Router) {
                this.user = this.afAuth.authState
                  .switchMap(user => {
                    if (user) {
                      return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
                    } else {
                      return Observable.of(null);
                    }
                  });
               }

googleLogin() {
  const provider = new firebase.auth.GoogleAuthProvider();
  return this.oAuthLogin(provider);
}


private oAuthLogin(provider){
  return this.afAuth.auth.signInWithPopup(provider)
    .then((credential) => {
      this.updateUserData(credential.user);
    });
}

private updateUserData(user){
  const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.id}`);

  const data: User = {
    uid: user.uid,
    email: user.email,
    displayName: user.displayName,
    photoURL: user.photoURL
  };

  return userRef.set(data);
}
} 

Click here for live demo

Answer №2

After receiving help from Kalamarico and Mirko Acimovic, I realized that I had missed a bracket at the bottom of my code. By adding it and replacing another one at the top, I thought all issues were resolved. However, there was still one more problem (refer to the bottom for details).

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

import * as firebase from 'firebase/app';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFirestore, AngularFirestoreDocument } from 'angularfire2/firestore';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/switchMap';


interface User {
  uid: string;
  email: string;
  photoURL?: string;
  displayName?: string;
  favouriteColor?: string;
}

@Injectable()
export class AuthService {

  user: Observable<User>;

  constructor(private afAuth: AngularFireAuth,
              private afs: AngularFirestore,
              private router: Router) {
                this.user = this.afAuth.authState
                  .switchMap(user => {
                    if(user) {
                      return this.afs.doc<User>(`users/${user.uid}`).valueChanges()
                    } else {
                      return Observable.of(null)
                    }
                  })

                }


googleLogin(){
  const provider = new firebase.auth.GoogleAuthProvider()
  return this.oAuthLogin(provider);
}


private oAuthLogin(provider){
  return this.afAuth.auth.signInWithPopup(provider)
    .then((credential) => {
      this.updateUserData(credential.user)
    })
}

private updateUserData(user){
  const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.id}`)

  const data: User = {
    uid: user.uid,
    email: user.email,
    displayName: user.displayName,
    photoURL: user.photoURL
  }

  return userRef.set(data)
}


}

Upon fixing the bracket issue, my terminal displayed the following error:

ERROR in node_modules/angularfire2/firebase.app.module.d.ts(10,22): error TS2420: Class 'FirebaseApp' incorrectly implements interface 'FirebaseApp'.
  Property 'automaticDataCollectionEnabled' is missing in type 'FirebaseApp'.

To resolve this, I simply ran npm update which successfully fixed the issue. The application is now functioning properly! Grateful for the assistance received!

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

Combining the Partial<CssStyleDeclaration> union type with a dictionary can lead to potential typing complications when the implicit any flag is

Using VueJS v-bind:style binding makes it possible to set CSS variables. I am attempting to create a union type that allows for the object passed to v-bind:style to retain typings for CssStyleDeclaration, while also being relaxed enough to accept an arbitr ...

React-bootstrap-table Axios delete operation causing [object%20Object] to be displayed in the browser console

I am having trouble executing a delete operation using axios on a react-bootstrap-table, and encountering this error in the console DELETE http://localhost:9000/api/terminals/[object%20Object] Uncaught (in promise) Error: Request failed with status cod ...

Implementing Formik in React for automatic updates to a Material-UI TextField when blurred

Presently, I am developing a dynamic table where users can simultaneously modify multiple user details in bulk (Refer to the Image). The implementation involves utilizing Material-UI's <TextField/> component along with Formik for managing form s ...

Unexpected Typescript error when React component receives props

I encountered an unexpected error saying ": expected." Could it be related to how I'm setting up props for the onChange event? Here is my code for the component: import React from "react"; interface TextFieldProps { label?: string; ...

Tips for effectively utilizing typescript interface with the OR operator

I'm a beginner when it comes to TypeScript. I have the following code snippet that I am working on: interface InitialData { active: boolean; status: boolean; } interface Item { id: number; name: string; Data: InitialData; } interface Main ...

Ways to store a component in cache once its route is triggered

There are 3 components in my project: 1 parent and 2 child components with router outlet. The child component becomes active whenever its route is called, sharing data using a service. Both of these child components have complex views. When switching bet ...

Angular 7 SPA encountering Media Type Not Supported 415 issue when communicating with .NET, despite successful request in Postman

My SPA is encountering a 415 Unsupported Media Type Error when it calls a specific endpoint in my .NET API that I recently implemented pagination for. Interestingly, the same call from Postman is successful without any errors. It's puzzling why the id ...

The function has been called but it did not return a

It seems that there is confusion surrounding the .toHaveBeenCalled() Matcher in Jasmine. While it should return a Promise that resolves when the function has been called, some users are experiencing it returning undefined instead. For example: it('sh ...

Retrieve the encrypted URL

I'm facing an issue with extracting parameters from an encrypted URL. When using the queryparams function, it only retrieves a portion of the URL after being decrypted. For instance, consider this example URL: http://localhost:4200/househouse? MGRjYjQ ...

Implementing automatic selection for MUI toggle buttons with dynamic data

By default, I needed to set the first toggle button as selected import * as React from "react"; import { Typography, ToggleButton, ToggleButtonGroup } from "@mui/material"; export default function ToggleButtons() { const dat ...

Navigating through Angular2 notifications using router chaining

I am currently working on a simple application form where, upon submission, the user is redirected to another page. My goal is to display a success message when the submit button is clicked. The code snippet below functions as expected, but there is an is ...

Retrieve information from a URL to transmit to a different page in NextJS using Typescript and AppRouter

I'm struggling with transitioning from the Home page to the Detail page. I've successfully passed data to the URL from the Home screen, but I'm having trouble accessing it in the Detail screen. I'm working with NextJS ver 13, using Type ...

The presence of an Angular Element within an Angular application can lead to a problematic cycle of constant reloading,

, I am encountering issues with integrating Angular Elements as plugins into my Angular application. The problem arises when building the element with "--prod" - it functions properly with "ng serve" in my development setup but causes infinite reloading wh ...

What could be causing jQuery to overlook this button?

Having some trouble with my angular, bootstrap, and jQuery setup. I can't get jQuery to select a button and trigger an alert when clicked: $('#some_button').click(function(e) { alert('testing'); }); <button id="some_but ...

React - Ensure useEffect is triggered only after state update

One of my components (ItemsIndex) is using a custom hook to fetch data from our API. However, the ItemsIndex's useEffect runs first, causing the DOM to not be filled with elements that could be scrolled into view. How can I make sure that the useItems ...

Retrieve all the items listed in the markdown file under specific headings

Below is an example of a markdown file: # Test ## First List * Hello World * Lorem Ipsum * Foo ## Second List - Item 1 ## Third List + Item A Part of Item A + Item B ## Not a List Blah blah blah ## Empty ## Another List Blah blah blah * ITEM # ...

Basic cordova application that transfers data from one page to another using typescript

Currently, I am developing an Apache Cordova application using TypeScript. However, I am facing a challenge in passing information from one HTML page to another using TypeScript. I would appreciate it if someone could guide me on the steps needed for nav ...

Steps for reinstalling TypeScript

I had installed TypeScript through npm a while back Initially, it was working fine but turned out to be outdated Trying to upgrade it with npm ended up breaking everything. Is there any way to do a fresh installation? Here are the steps I took: Philip Sm ...

Can Angular Universal be configured to have all HTTP Requests originate from the Server instead of the Client's Browser in an Angular Application?

With specific requirements in mind, I require the Angular application to carry out all requests on the server rather than on the client's browser. After implementing SSR (Server-Side Rendering) through Angular Universal on my application, I anticipat ...

Retrieve the values stored under the "kilos" key for every object in the dataset

Recently, I stumbled upon the following code snippet: data = [ 0: {kilos: 10}, 1: {other:1, kilos: 5}, 2: {other:2, kilos:6} ] After analyzing it, I realized that I need to extract all the values associated with the "kilos" keys and then calculat ...