0
votes

I'm using a service(An auth service) to check whether the user is saved in the localstorage or not to save a new one or fetch if the user is already saved now I want to build with Angular universal so the localstorage causes an error so downloaded the package @ng-toolkit/universal and I inject the localstorage just like the documentation but it causes all the functions using the localstorage to throw and error

This is for a new Angular app using Angular 8, Angular Universal, @ng-toolkit/universal

import { LOCAL_STORAGE } from "@ng-toolkit/universal";

@Injectable({
  providedIn: "root"
})
export class AuthService {
  user: User;
  userLoggedIn = new Subject();

  constructor(
    private _http: HttpClientService,
    @Inject(LOCAL_STORAGE) public localStorage
  ) {}
  get isLogin() {
    if (localStorage.getItem("user")) {
      this.user = JSON.parse(localStorage.getItem("user"));
      this.userLoggedIn.next();
      return JSON.parse(localStorage.getItem("user"));
    }
  }

  register(body) {
    return this._http.post(body, "user/register");
  }
  login(body) {
    return this._http.post(body, "user/login");
  }
  saveUser(user) {
    localStorage.setItem("user", JSON.stringify(user));
    this.user = user;
  }
  updateProfile(body) {
    return this._http.post(body, "auth/applicant/profile/create-general-info");
  }

  get Token() {
    if (localStorage.getItem("user")) {
      try {
        return JSON.parse(localStorage.getItem("user")).token;
      } catch (e) {
        console.log(e);
      }
    }
  }

  // Get User Role
  get Role() {
    if (localStorage.getItem("user")) {
      try {
        return JSON.parse(localStorage.getItem("user")).role.role;
      } catch (e) {
        console.log(e);
      }
    }
  }

  get UserId() {
    if (localStorage.getItem("user")) {
      return JSON.parse(localStorage.getItem("user")).id;
    }
  }
  get User() {
    if (localStorage.getItem("user")) {
      return JSON.parse(localStorage.getItem("user"));
    }
  }

I expect the functions to work normally and correctly just like before the injection but they're not now the functions throw errors mostly isLogin and Token

1
Can you post the error here?ymssa___

1 Answers

0
votes

the answer is no. You cannot use localStorage in Angular Universal. The special injection is there only to be able to compile the code. But the localStorage only exists in the user's browser and is not available on the server. You can use isPlatformBrowser to check whether the localStorage is available. It this described in this article