Angular subscribing best approach

Discussão em 'Angular' iniciado por Robert Crx, Novembro 20, 2024.

  1. Robert Crx

    Robert Crx Guest

    I wonder what should be the best option to subscribe or to handle data across application, in my case, a user data should be subscribed inside service or should I make a subscribe call to my API every time I enter different admin components?

    At the moment I chose to make a single call to retrieve the user and store the data inside an behavior subject.

    auth.service.ts:

    currentUserSubject = new BehaviorSubject<any>(null);
    currentUser$ = this.currentUserSubject.asObservable();

    currentUserStateSubject = new BehaviorSubject<any>(false);
    currentUserState$ = this.currentUserStateSubject.asObservable();

    isLoadingSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(true);
    isLoading$ = this.isLoadingSubject.asObservable();

    // here I check for user state , I automatically update user across all // components
    // and it will render only the first time component is loaded (excluding components
    // that have providers with this class)

    constructor(
    private http: HttpClient,
    public router: Router,
    ) {
    if (this.isLoggedIn()) {
    this.getUser().subscribe();
    } else {
    this.isLoadingSubject.next(false);
    this.currentUserStateSubject.next(false);
    this.currentUserSubject.next(null);
    }
    }


    /**
    * -=[### AUTH - GET USER DETAILS ###]=-
    * Retrieve user data
    * @return {Observable<any>}
    */
    public getUser(): Observable<any> {
    const body = { server_key: this.serverKey };
    this.isLoadingSubject.next(true);
    const loadingTimer = timer(500);
    return loadingTimer.pipe(
    switchMap(() =>
    this.http.post(environment.getUser, body, this.httpOptions).pipe(
    catchError((error: any) => {
    console.log(error);
    this.isLoadingSubject.next(false);
    this.currentUserSubject.next(null);
    this.currentUserStateSubject.next(false);
    this.logoutUser();
    return of(null);
    }),
    timeout(10000),
    catchError((error: any) => {
    if (error instanceof TimeoutError) {
    // Handle timeout error here
    console.log('Request timed out', error);
    // You can throw a custom error here if needed
    }
    return throwError(error); // Rethrow the error
    }),
    tap((user) => {
    this.isLoadingSubject.next(false);
    this.currentUserSubject.next(user);
    this.currentUserStateSubject.next(true);
    console.log(this.currentUserSubject.value);
    })
    )
    )
    );
    }


    In my component I will only use this syntax:

    this.currentUser$ = this.authService.currentUser$;
    this.isLoggedIn$ = this.authService.currentUserState$;
    this.isLoading$ = this.authService.isLoading$;


    I need to know if my approach is good or should I subscribe every time to update data across components ? Thank you.

    Continue reading...

Compartilhe esta Página