Angular - идентификатор пользователя firebase не определен при навигации, возвращается после обновления - PullRequest
0 голосов
/ 23 февраля 2020

Таким образом, мое приложение предназначено для добавления объекта в базу данных Firebase на основе идентификатора пользователя, но работает только тогда, когда я обновляю sh страницу - когда я попадаю на страницу через навигацию, он говорит, что мой идентификатор пользователя не определен.

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>;
  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('Succesful 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('Succesful 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;
  }
}

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;
      }
    )
  }

}

По какой-то причине моя подписка на userID не работает должным образом

Заранее спасибо за помощь

Ответы [ 2 ]

0 голосов
/ 24 февраля 2020

Я только что запустил npm update, и это сработало. Понятия не имею, почему.

0 голосов
/ 23 февраля 2020

У вас есть две службы, одна - AngularFireAuth, другая - AuthService. Я не уверен, что происходит внутри AuthService, я думаю, что вы можете обнаружить изменение состояния авторизации и установить объект пользователя, взаимодействуя с бэкендом.

Возможно, вы не синхронизировали точки получения объекта пользователя и навигации. Таким образом, пользователь еще не настроен, пока вы не перейдете на страницу.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...