I am in the process of starting a new angular project, but I'm facing difficulties in importing the localStorage feature. I referred to an existing project that utilized localStorage in the following way:
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Router } from '@angular/router';
import { AuthenticationService, LoginModel } from '../_libraries/card-system-core';
export class AuthenticationHelper {
//...
constructor(private authService: AuthenticationService, private router: Router) {
this.currentUserSubject = new BehaviorSubject<AuthInfo>(JSON.parse(localStorage.getItem(this.STORAGE_NAME)));
this.currentUserRouteSubject = new BehaviorSubject<RouteInfo[]>(JSON.parse(localStorage.getItem(this.STORAGE_ROUTES_NAME)));
this.currentUser = this.currentUserSubject.asObservable();
this.currentUserRoute = this.currentUserRouteSubject.asObservable();
}
//...
The old project was written in TypeScript, but when attempting to implement localStorage in my new project, I encountered the following error: https://i.sstatic.net/eMvxU.png
I was hoping that it would be linked properly to allow for "go to definition" functionality, as seen here: https://i.sstatic.net/Spp39.png
I discovered a line in the old project's package.json file under "peerDependencies":
"dependencies": {
"tslib": "1.10.0"
},
"devDependencies": {
"ts-node": "~5.0.1",
"tslint": "~6.1.0",
"typescript": "~4.2.4"
},
"peerDependencies": {
"tslib": "1.10.0"
}
However, using "peerDependencies" with "tslib": "2.3.0" did not work in my new project. It only worked when I reverted to version 1.10.0 under "peerDependencies" in my project setup:
"dependencies": {
"tslib": "^2.3.0",
},
"devDependencies": {
"ts-node": "^10.9.1",
"typescript": "~4.7.2"
}
So, my question is why was it necessary to specify "tslib": "1.10.0" in peerDependencies to make localStorage work? I'm unsure of the relationship between TypeScript, peerDependencies, and tslib. Is it not standard practice to use peerDependencies for "tslib": "2.3.0" when utilizing localStorage?
Eventually, I made changes to my code as follows. Thank you for your assistance:
let storagedName = localStorage.getItem(this.STORAGE_NAME);
let storagedRouteName = localStorage.getItem(this.STORAGE_ROUTES_NAME);
let emptyUser:AuthInfo = {
accessToken: "",
routes: [],
twoFA: false,
forgotPassword: false,
errorMessage: ""
}
this.currentUserSubject = new BehaviorSubject<AuthInfo>(emptyUser);
if(storagedName)
this.currentUserSubject = new BehaviorSubject<AuthInfo>(JSON.parse(storagedName));
this.currentUserRouteSubject = new BehaviorSubject<RouteInfo[]>([]);
if(storagedRouteName)
this.currentUserRouteSubject = new BehaviorSubject<RouteInfo[]>(JSON.parse(storagedRouteName));