Exploring the use of global variables in Firebase authentication with TypeScript

I declared a variable called user outside of the specified scope. However, I am encountering difficulties in accessing this.user within the function

firebase.auth().signInWithPopup(provider).then((result) => {
. It keeps displaying as undefined.

    import { ...everything } from 'everything';    

    @Component({
      selector: 'page-login',
      templateUrl: 'login.html',
    })
interface User{
  email: string;
  displayName: string;
  uid?: string;
  photoUrl?: string;
}
    export class LoginPage {

      user:User;

      constructor(...every) {
      }

      validateForm(form){
        if(form.valid){
            var provider = new firebase.auth.GoogleAuthProvider();
            provider.addScope('https://www.googleapis.com/auth/plus.login');
            firebase.auth().signInWithPopup(provider).then((result) => {
                const token = result.credential.accessToken;
                const userData = result.user;
                this.user.email = userData.email;    
            }).catch(function(error) {
            });
          }
        }
      }
    }

Answer №1

import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';

export class LocalAuthService {

  constructor(private afAuth: AngularFireAuth) { }

  userID: string;
  userName: string;

  public register(email: string, password: string) {

    console.log('Executing the service method');
      //This function will sign up a new user
      this.afAuth.auth.createUserWithEmailAndPassword(email, password).catch( function(error) {

        console.log('An error occurred' + error.message);
        console.log('Error code: ' + error.code);

      });

      this.afAuth.auth.onAuthStateChanged( function(user) {
        if (
            this.userID = user.uid;
            this.userName = user.displayName;

        }
      });

  }

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

Restoring ngModel value in Angular's input field back to its original state

Currently, I am utilizing Angular 10 in conjunction with Nebular 6. My goal is to implement the following: Within a form, there exist two input date fields, labeled as start of project and end of project. Should a user attempt to input an invalid date (u ...

Is it possible to configure npm to publish to an organization different from the one automatically detected from package.json?

We are looking to implement a process in our open source project where all Pull Requests will be published to npm using CI/CD. To reduce the potential for supply chain attacks, we aim to deploy to a separate organization. Can this be achieved without makin ...

Send an API request using an Angular interceptor before making another call

Within my application, there are multiple forms that generate JSON objects with varying structures, including nested objects and arrays at different levels. These forms also support file uploads, storing URLs for downloading, names, and other information w ...

Special scenarios requiring OnPush Change Detection

I'm currently building an Angular 2 application using ngrx, and I've been intrigued by the concept of OnPush change detection for optimizing performance. After reading multiple articles on the topic, it seems that the general consensus is: "If a ...

Downloading a CSV file using Angular 8 and Django RestFramework

I am a beginner in Angular and I'm looking to implement a feature where users can download a CSV file upon clicking a download button. Django viewset @action(detail=False, methods=['get']) def download_csv(self, request): data = { ...

What impact does nesting components have on performance and rendering capabilities?

Although this question may appear simple on the surface, it delves into a deeper understanding of the fundamentals of react. This scenario arose during a project discussion with some coworkers: Let's consider a straightforward situation (as illustrat ...

Angular 5: Unable to add a destroyed View to a ViewContainer

I encountered a new error in my Angular application that I haven't seen before. The issue is arising from this specific line in the Angular source code. This error occurs when I log out and then log back into my app. While on a certain route, there i ...

Ways to transmit information or notifications from a service to a component

Currently, I am utilizing Angular 6 and have the upload file control on three different screens (three various components). Each of these screens calls the same method UploadFile(). The main issue arises when I need to make any changes to this method, as ...

Angular-cli working in conjunction with an express project

I am currently working on a project that involves Express, MongoDB, and the REST API. I now want to integrate Angular into the project using angular-cli. However, I have several questions about the process. Here is the current structure of my project: htt ...

When attempting to pass props to children, Typescript triggers an error message

I am facing an issue with a component that renders a child based on the specific "league" a user is viewing, such as MLB. Typescript is throwing an error because I am not passing the correct props to the child component. However, the parent component has t ...

Passing a username and password to an API in Angular 6: Step-by-step guide

Can someone assist me with this problem? I am struggling to pass the username and password in my API request for a list of homes. Every attempt I've made has resulted in an unauthorized access error. How do I correctly include the user credentials (pe ...

Group of objects containing an inner group of objects

Here is an array of objects that I am working with: let prova: ActiveRoute[] = [ { path: '/Root', method: 'GET', children: [ { path: '/Son', method: 'GET', chi ...

Sending text containing HTML elements from the parent component to the child component

I'm facing a challenge where I need to transfer a string from my parent component to my child component. The string includes HTML tags with an HTML entity. Here's how it looks in the parent template: <child-component i18n-componentContent=&quo ...

The functionality to close a Mat dialog is not functioning properly on Angular 11 with Material 11

I am trying to close the dialog by calling the close function of MatDialogRef instance, but unfortunately it is not working as expected. Within my ShareModule, there are components like HeaderCompose and LoginComponent. The HeaderComponent utilizes the Lo ...

Typescript interface design for nested objects in a hierarchical structure

When data is received from the server in JSON format, it typically looks like the example below (details have been modified): { "apple": { "fruitName": "apple", "types": { "greenApple": { ...

What is the reason for the allowance of numeric keys in the interface extension of Record<string, ...>

I am currently working on a method to standardize typing for POST bodies and their corresponding responses with API routes in my Next.js application. To achieve this, I have created an interface that enforces the inclusion of a body type and a return type ...

Unlocking the Power of Asynchronous Data in Angular's Dynamic Form Patterns

Utilizing the dynamic form pattern in Angular has been incredibly helpful for our team. By defining our controls in ngOnInit, the form is dynamically constructed based on our needs. However, we've encountered a challenge with forms that require initia ...

Ways to improve the feedback for Typescript when dealing with the potential existence of a nested method

Recently encountered a critical bug that I believe could have been identified with the right TypeScript setup. Struggling to come up with a suitable title, so please bear with me. While initializing a widget app, similar to a chat app loaded by a parent a ...

What is the best way to prevent re-initialization of a child component when there are changes in the

I'm currently developing an application that features a wall similar to Facebook, complete with post components (each post displaying a like counter) and nested comment components which are loaded on demand with a button within the post. My implementa ...

Switch branches to projects without node_modules installed

Is there a better way to checkout a project that had node_modules in .gitignore? I have 2 computers and currently follow the following steps: Commit the project from computer 1 to GitHub Create a new angular project with the same name and folder structur ...