angular 2 localstorage找不到名字

时间:2017-04-08 21:21:02

标签: angular

我正在使用角度CLI,我正在尝试使用localStorage作为注册组件,但这不起作用,它说无法找到名称'localStorage' 这是我的服务

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 });
    }
  }

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

SetItem的类型为void,不返回任何内容

(a,b)

答案 1 :(得分:0)

你的代码应该是:

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 });
    }
  }

<小时/> 但为什么这是if (currentUser && currentUser.token)? 如果if条件是关键的,那么最好将localStorage.setItem('currentUser',user)行移入其中。

答案 2 :(得分:0)

也许您必须在tsconfig.json中添加 lib:dom

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

(来源:tsconfig.json