刷新后清除Angular 2 LocalStorage

时间:2017-04-21 10:08:50

标签: javascript angular

这里有点奇怪的小东西:)

所以我正在做的是在尝试登录用户时,我想存储access_token并在localStorage中过期。哪个工作“好”。但是如果我刷新页面,如果我想在单击登录按钮后看到添加的令牌,那么令牌也会消失我需要重新启动控制台(F12)才能看到它们。你能看到我做错了吗?

服务

import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { AppSettings } from '../AppSettings.component';
import { Observable } from 'rxjs';

@Injectable()
export class UserService {

    private headers = new Headers({
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache'
    });

    constructor(private http: Http) {
    }

    loginUser(email: string, password: string, remember: boolean) {
        var data = {
            'email': email,
            'password': password,
            'client_id': AppSettings.CLIENT_ID,
            'client_secret': AppSettings.CLIENT_SECRET,
            'remember': remember
        };
        return this.http.post(AppSettings.HOST + 'auth/login', data, {headers: this.headers})
            .map(
                (response: Response) => {
                    const loginData = response.json().Result;
                    return loginData;
                })
            .do(
                responseData => {
                    localStorage.setItem('token', JSON.stringify(responseData.access_token));
                    localStorage.setItem('expires', JSON.stringify(responseData.expires));
                }
            );
    }
}

如果我刷新页面,所有令牌也都消失了。

的package.json

"dependencies": {
    "@angular/common": "^2.4.8",
    "@angular/compiler": "^2.4.8",
    "@angular/core": "^2.4.8",
    "@angular/forms": "2.4.8",
    "@angular/http": "^2.4.8",
    "@angular/platform-browser": "^2.4.8",
    "@angular/platform-browser-dynamic": "^2.4.8",
    "@angular/router": "^3.4.8",
    "angular2-social-login": "^2.1.0",
    "core-js": "^2.4.1",
    "rxjs": "5.1.1",
    "zone.js": "^0.7.7"
  }

组件

import { Component } from '@angular/core';
import { UserService } from '../../services/user.service';
import { Response } from '@angular/http';

@Component({
    selector: 'login-layout',
    templateUrl: './app/views/login/login.component.html',
    providers: [ UserService ]
})

export class LoginComponent {
    user: {};
    email: string = '';
    password: string = '';
    remember: boolean;

    constructor(private _userService: UserService) {}

    loginForm() {
        this._userService.loginUser(this.email, this.password, this.remember).subscribe(
            responseData => console.log(responseData),
            error => console.log(error)
        );
    }


}

修改

确定在Firefox上查看。即使刷新后,令牌也能正确存储。好像Chrome问题。之前有其他人来过这个吗?

1 个答案:

答案 0 :(得分:0)

Ok ...发现访问localStorage crossbrowser的问题,您需要使用localStorage["key"]

愚蠢的错误.... :)

可在此StackOverflow answer

中找到更多信息