Issue with Angular and Firebase user ID being undefined when navigating, but resolves after refreshing the page

My application is designed to add an object to a Firebase database based on user ID. However, I am facing an issue where the process only works when I manually refresh the page. If I navigate to the page through the app's navigation, it shows that the user ID is undefined.

In my auth.service.ts file:

import { Router } from '@angular/router';
import { User } from './interface/user';
import { Observable, Subject } from 'rxjs';
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  user: Observable<User | null>;
  private logInErrorSubject = new Subject<string>();
  private signUpErrorSubject = new Subject<string>();

  constructor(public afAuth: AngularFireAuth, private router: Router) {
    this.user = this.afAuth.authState;
  }

  getUser(){
    return this.user;
  }

  SignUp(email: string, password: string) {
    this.afAuth
      .auth
      .createUserWithEmailAndPassword(email, password)
      .then(res => {
        console.log('Successful Sign Up', res);    
        this.router.navigate(['/welcome']);
      })
      .catch (error => this.signUpErrorSubject.next(error.message));
    console.log(this.signUpErrorSubject);
  }

  Logout() {
    this.afAuth.auth.signOut();
  }

  login(email: string, password: string) {
    this.afAuth
      .auth.signInWithEmailAndPassword(email, password)
      .then(res => {
        console.log('Successful Login', res);     
        this.router.navigate(['/welcome']);
      }
      )
      .catch(error => this.logInErrorSubject.next(error.message));

  }

  public getLoginErrors(): Subject<string> {
    return this.logInErrorSubject;
  }
  
  public getSignUpErrors(): Subject<string> {
    return this.signUpErrorSubject;
  }
}

In temperature.component.ts :

import { AuthService } from './../auth.service';
import { Weather } from './../interface/weather';
import { Observable } from 'rxjs';
import { WeatherService } from './../temp.service';
import { Component, OnInit, } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-temperatures',
  templateUrl: './temperatures.component.html',
  styleUrls: ['./temperatures.component.css']
})
export class TemperaturesComponent implements OnInit {

  constructor(private authService: AuthService, private route: ActivatedRoute, private weatherService: WeatherService) {}

  userId: string;
  likes = 0;
  temperature;
  image;
  city;
  tempData$: Observable<Weather>;
  errorMessage: string;
  hasError: boolean = false;
  saveBtn: string = "Save";
  
  addLikes() {
    this.likes++;
  }

  saveCity() {
    if(this.userId)
      this.weatherService.addCity(this.userId, this.city, this.temperature);
  }

  ngOnInit() {
    this.authService.user.subscribe(user => {
      if (user) {
        this.userId = user.uid;
      }
    });

    //this.temperature = this.route.snapshot.params.temp;
    this.city = this.route.snapshot.params.city;

    this.tempData$ = this.weatherService.searchWeatherData(this.city);

    this.tempData$.subscribe(
      data => {
        console.log(data);
        this.temperature = data.temperature;
        this.image = data.image;
      },
      error => {
        console.log(error.message);
        this.hasError = true;
        this.errorMessage = error.message;
      }
    );
  }
}

It seems like my subscription to the userID is not working as expected. Any help would be greatly appreciated. Thank you in advance!

Answer №1

Within your system, there are two key services at play - AngularFireAuth and AuthService. It appears that AuthService is responsible for managing authentication state changes and populating the user object by communicating with the backend.

However, it seems that there may be a synchronization issue between when the user object is received and navigating to another page. As a result, the user may not be properly set until you navigate to a specific page within the application.

Answer №2

After executing npm update, it magically resolved all the issues without any explanation.

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

The Ins and Outs of Selecting the Correct Module to Attach a Controller in NestJS CLI

My experience with NestJS has been great so far, especially the Module system and how easy it is to parse requests. However, I have a question about the NestJS CLI. Let's say I have multiple modules. When I create a controller using the command "nes ...

The world of TypeScript generics and derived data types

I'm looking to streamline the process of calling multiple functions by creating a function that handles this task. These functions all require similar business logic and cleanup operations. function foo(arg: number) { // perform actions using arg ...

Exploring Angular's ngFor feature in building a dynamic accordion menu that automatically closes one panel and opens another when clicked

The Angular Material accordion component is a key feature in my Angular project. Utilizing an ngFor loop to iterate through the information stored in menuItems, I dynamically create a new expansion panel for each item. With two components in play, I seaml ...

Issue with NgModule in Angular application build

I'm facing an issue with my Angular application where the compiler is throwing errors during the build process. Here's a snippet of the error messages I'm encountering: ERROR in src/app/list-items/list-items.component.ts:9:14 - error NG6002 ...

In TypeScript, leveraging the spread operator to determine the largest value in an array containing nullable numbers

Having an array of nullable numbers presented in the following way: let myArray : Array<number | null> = [1,2,null,4,null,5]; let maximumOfMyArray = Math.max(...myArray); // Type null is not assignable to type number I am content with JavaScript tre ...

Utilizing Gulp to Convert TypeScript Exports into a JSON File

I have a set of TypeScript files, some of which export a specific variable - named APIS - which contains an array of objects. My goal is to extract the values from all of these exports and save them into a JSON file using Gulp. Let's consider a direc ...

How do I specify TypeScript types for function parameters?

I've created a function and used TypeScript to define parameter types: const handleLogin = async ( e: React.FormEvent<EventTarget>, navigate: NavigateFunction, link: string, data: LoginDataType, setError: React.Dispatch<Re ...

Navigating through an array to extract necessary information within an Angular framework

Below is the JSON data I have: [{ "_id": 1, "Name": "x", "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6dce6c3d6d5cfcac9c888c5c9cb">[email protected]</a> ", "Designation": "Manager", "Projec ...

Encountering the error message "No 'Access-Control-Allow-Origin' header is found on the requested resource."

While working with Angular on the frontend and Java Spring on the backend, I encountered an error message stating: 'No 'Access-Control-Allow-Origin' header is present on the requested resource.'. Even though CORS is enabled in my config ...

Which data type should be used with the useRef hook for iframes?

Looking to avoid using the any type, but not sure which type definition to use instead for this situation: const iframe = useRef<any>(); <iframe ref={iframe} sandbox='allow-scripts' srcDoc={rootHtml} /> Want Typescript t ...

Merging Type-GraphQL and Typegoose through a Variety of Decorators

Using a combination of Type-GraphQl and Typegoose, I aim to streamline my data definitions by consolidating them into one source for both GraphQL schemas and Mongoose queries. Is it feasible to merge the two libraries in a way that allows me to describe bo ...

What is the best way to extract specific fields from nested tables using MikroORM?

I am currently facing challenges while attempting to extract specific fields from nested join results. Within my entities, there is a "Restaurant" entity that has a one-to-many relationship with "Product". Each "Product" has a many-to-many relationship wi ...

The issue of the Angular service being consistently undefined arises when it is invoked within an

I have already researched numerous other SO questions, but none of the solutions worked for me. My goal is to implement an async validator that checks if a entered username already exists. However, every time I type a letter into the input field, I encoun ...

Exploring the nesting of client components in Next.jsIf you are

Exploring the realm of NextJS and React, I find myself delving into the realm of client components. One such client component I'm working with is called Form.jsx. It looks something like this: export default function FormHome() { ... a plethora of ...

Tips for configuring Visual Studio Code to utilize path mappings for handling automatic imports

In order to streamline my project and avoid messy paths, I am implementing absolute paths that will allow for consistent imports regardless of the file's location in the project tree. For this purpose, I made adjustments to the tsconfig.json: "paths ...

Encountering a Problem with Angular 2 RC HTTP_PROVIDERS

I recently upgraded my Angular 2 application to the RC version. Everything was working smoothly until I included HTTP_PROVIDER and created a service.ts file. However, now I am encountering an error: (index):14 Error: SyntaxError: Unexpected token <( ...

Utilizing Angular 4's routing feature to pass parameters just like a

Greetings! I hope you are doing great. Currently, I am working on building an application using Angular 4 and I am facing a challenge regarding passing parameters in my routes, similar to how POST parameters are passed in HTTP requests. Can anyone provide ...

Decoding request header in Angular during app initialization

Currently, I have three domain names registered with Godaddy and they are all directing to the same server that is hosting my Angular 2 application. I am curious if there is a method to examine the request header in order to identify which of the three d ...

Error in Angular-CLI and TypeORM: Module parsing failed due to the presence of 'import' and 'export' statements, which are only allowed with 'sourceType: module'

When attempting to integrate typeorm into a new angular-cli project, I encounter a compiler error as soon as I reference typeorm. ./node_modules/typeorm/browser/index.js:3:0 - Error: Module parse failed: 'import' and 'export' may appear ...

REDUX: The dispatch function is failing to update the store

Working on a project developing a chrome extension that involves dispatching functions in popup.tsx. However, the store does not update when I try to dispatch. Interestingly, the same code works perfectly fine in the background page. Any suggestions on wha ...