Title: Angular - firebase userID undefined when navigating, comes back after refreshing
Tags: angular;typescript;firebase;firebase-authentication;angularfire2
Question: So my app is meant to add an object to a firebase database based on user ID, but only works when I refresh the page - when I get to the page via navigation it says that my user ID is undefined.
auth.service.ts:
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&gt;;
private logInErrorSubject = new Subject<string&gt;();
private signUpErrorSubject = new Subject<string&gt;();
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 =&gt; {
console.log('Succesful Sign Up', res)
this.router.navigate(['/welcome']);
}
).catch (error =&gt; 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 =&gt; {
console.log('Succesful Login', res)
this.router.navigate(['/welcome']);
}
).catch(error =&gt; this.logInErrorSubject.next(error.message));
public getLoginErrors(): Subject<string&gt; {
return this.logInErrorSubject;
public getSignUpErrors(): Subject<string&gt; {
return this.signUpErrorSubject;
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&gt;;
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 =&gt; {
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 =&gt; {
console.log(data);
this.temperature = data.temperature;
this.image = data.image;
},
error =&gt; {
console.log(error.message);
this.hasError = true;
this.errorMessage = error.message;
}
for some reason it seems my subscription to userID does not work as intended
Thanks in advance for helping


Here is another answer: Your have two services, one is AngularFireAuth, another one is AuthService.
I am not sure what's happening inside AuthService, i think you might detect auth state change and set user object by interacting with backend.
You might not synced the points of receiving user object and the navigation.
So user is not set yet until you navigated to a page.

Here is another answer: I just ran npm update and it worked. No idea why.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2020:00:02/23/20', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<angular><typescript><firebase><firebase-authentication><angularfire2>', 'Title': 'Angular - firebase userID undefined when navigating, comes back after refreshing', 'ViewCount': 300, 'id': 60364120, 'user_AboutMe': None, 'user_AccountId': 13235162.0, 'user_DisplayName': 'Idan Brinza', 'user_Reputation': 21.0, 'user_Views': 3.0, 'user_id': 9557529.0}}