Service class and Rxjs subject in Angular for reactivity

77 Views Asked by At

I'm new to Angular and I'm trying to learn a few things. I made a system for login/register where a user can login or register. I'm trying now to make a way to persist the user to be logged in on refresh by checking if he has a token in the localStorage.

I did that, but, my question for you is that:

I have a authService that has a property userFetched: boolean = false. I inject the authService in the app.component.ts and inside the app component I have ngOnInit where I send a simple post request to the backend to verify the token (if he has), then if all ok, I set this.authService.userFetched = true from within app component.

Then in my app.component.html it seems to reflect the changes, also in other components as well. It seems to be reactive when the value changes/update.

Is this a good approach or should I use Subject using Rxjs instead of simple service property?

// app.component.ts

import { Component, OnInit } from "@angular/core";
import { AuthService } from "./services/auth.service";

@Component({
    selector: "app-root",
    templateUrl: "./app.component.html",
    styleUrls: ["./app.component.css"],
})
export class AppComponent implements OnInit {
    constructor(protected authService: AuthService) {}

    ngOnInit(): void {
        console.log("called");
        console.log("called with:", this.authService.userFetched);
        
        if(localStorage.getItem('token') !== null) {
          // bla bla...
          this.authService.userFetched = true;
        }
    }
}

// app.component.html

<div>User fetched: {{ authService.userFetched }}</div>
<app-navigation></app-navigation>
<router-outlet></router-outlet>


// AuthService

import { Injectable, OnInit } from "@angular/core";
import { Observable, of, throwError } from "rxjs";
import { HttpClient, HttpErrorResponse, HttpHeaders } from "@angular/common/http";
import { catchError } from "rxjs/operators";

interface User {
    id: number;
    name: string;
    email: string;
}

interface UserCredentials {
    name: string;
    password: string;
}

@Injectable({
    providedIn: "root",
})
export class AuthService implements OnInit {
    public userFetched: Boolean = false;

    constructor(private http: HttpClient) {}
}

// rest of the code...

I've made also a way to change (just for test) the userFetched when you click a button, and it also works. But is it a good approach?

0

There are 0 best solutions below