Angular - BehaviorSubject is always undefined in service

Discussão em 'Angular' iniciado por Jonathan Sigg, Janeiro 23, 2025.

  1. I have some problem with this auth service.

    I created one for authentication. I want to set my user if i can log in. On the call, when i want to call this.user.next(user), i get an error. The error says, that this.user is undefined. But why? I have declared it.

    How can i fix this?

    Here is my code:

    import { HttpClient, HttpErrorResponse, HttpParams } from "@angular/common/http";
    import { Injectable } from "@angular/core";
    import { BehaviorSubject, catchError, tap, throwError } from "rxjs";
    import { User } from "./user.model";

    export interface AuthResponseData {
    ...
    }
    @Injectable({
    providedIn: 'root'
    })
    export class AuthService {
    private apiKey = '...'
    user = new BehaviorSubject<User>(null)

    constructor(
    private http: HttpClient
    ) {}

    signup(email: string, password: string) {
    ...
    ).pipe(
    catchError(this.handleError),
    tap(this.handleAuthentication)
    )
    }

    login(email: string, password: string) {
    ...
    ).pipe(
    catchError(this.handleError),
    tap(this.handleAuthentication)
    )
    }

    private handleAuthentication(response: AuthResponseData) {
    const { email, localId, idToken, expiresIn } = response
    const expires = new Date(new Date().getTime() + +expiresIn * 1000)
    const user = new User(email, localId, idToken, expires)
    this.user.next(user)
    }

    private handleError(errorResponse: HttpErrorResponse) {
    ...
    }
    }

    Continue reading...

Compartilhe esta Página