Jonathan Sigg
Jonathan Sigg

Reputation: 350

Angular - BehaviorSubject is always undefined in service

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) {
    ...
  }
}

Upvotes: 0

Views: 64

Answers (1)

vitaliy kotov
vitaliy kotov

Reputation: 647

Cause when you provide a callback this way, you should also bind context to it.

So your taps should be:

tap(this.handleAuthentication.bind(this)

Upvotes: 0

Related Questions