Angular 2 localstorage cannot find name

I am using angular CLI and I am trying to use localStorage for the registration component but it doesn't work says "Can't find the name 'localStorage', This is my service

create(user: User) {
    return this.http.post('/signup', user, this.jwt(user)).map((response: Response) => response.json());
  }

  private jwt(user) {
    let currentUser = localStorage.setItem('currentUser', user);
    if (currentUser && currentUser.token) {
        let headers = new Headers({ 'Authorization': 'Bearer ' + currentUser.token });
        return new RequestOptions({ headers: headers });
    }
  }

      

how can i fix this?

+3


source to share


3 answers


SetItem is void and returns nothing



setItem(key: string, data: string): void;

      

+1


source


your code should be:

create(user: User) {
    return this.http.post('/signup', user, this.jwt(user)).map((response: Response) => response.json());
  }

  private jwt(user) {
    let currentUser = user
    localStorage.setItem('currentUser', user);
    if (currentUser && currentUser.token) {
        let headers = new Headers({ 'Authorization': 'Bearer ' + currentUser.token });
        return new RequestOptions({ headers: headers });
    }
  }

      




but why exactly this if (currentUser && currentUser.token)

? if this condition if

is critical, then it is better to move the local line localStorage.setItem ('currentUser', user) into it.
0


source


Maybe you need to add lib: dom to tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "../dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "es2016",
      "dom"
    ]
  }
}

      

(source: tsconfig.json )

0


source







All Articles