如何在服务/组件角度2中获取本地存储数据

时间:2016-12-02 11:18:05

标签: angular local-storage

我是angular2的新手并尝试在登录后将数据保存在本地存储中,并且它对我来说工作正常,我可以从同一服务的本地存储中获取该项目,但是在本地存储中存在问题其他服务/组件。这是我的代码。

我在login.service中设置了值但无法进入登录组件。请看看是否可以帮助我。

login.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'
import configApp = require('../_configs/app.settings');
//import '../assets/frontend/custom/js/jquery.toaster.config.js';
declare function maketoast(status: string, message: string) : void;


@Injectable()
export class AuthenticationService {

constructor(private http: Http) { }

 login(username: string, password: string) {

   // console.log(configApp.apiUrl+/test);

    return this.http.post(configApp.apiUrl+"/api/login", JSON.stringify({ username: username, password: password }))
        .map((response: Response) => {

            // login successful if there's a jwt token in the response
            let user = response.json();

            console.log(user.status);
            if(user.status == false){

                maketoast(user.toaster_status, user.message);
                event.stopImmediatePropagation;
                event.preventDefault();
                event.stopPropagation();

            }

            //console.log(user.token);
            if (user && user.token) {

                // store user details and jwt token in local storage  to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify(user));
                maketoast(user.toaster_status, user.message);
                console.log(window.localStorage.getItem('currentUser'));
                event.stopPropagation();
            }
        });
}

   logout() {
    // remove user from local storage to log user out
    localStorage.removeItem('currentUser');
   }
}

login.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { AlertService, AuthenticationService } from '../_services/index';
//import { AppSettings,IEnvVars } from '../_configs/app.settings';


@Component({
  moduleId: module.id,
  templateUrl: '../templates/login.component.html',
  providers:[AlertService, AuthenticationService]
})

 export class LoginFormComponent implements OnInit {
   model: any = {};
   loading = false;

 constructor(
    private router: Router,
    private authenticationService: AuthenticationService,
    private alertService: AlertService) {

    **please see here**
    let value: string = localStorage.getItem("currentUser");
    console.log(value);
}

ngOnInit() {
    // reset login status
    this.authenticationService.logout();
}

login() {

    this.loading = true;
    this.authenticationService.login(this.model.username,       this.model.password)
        .subscribe(
            data => {

                this.router.navigate(['/']);
            },
            error => {
                this.alertService.error(error);
                this.loading = false;
            }
        );
    }
}

3 个答案:

答案 0 :(得分:4)

是的,它现在正在工作。实际上,我们必须定义全局变量并将本地存储数据存储在该变量中。现在我们可以在组件的任何地方使用它。感谢。

public userData: any;
public userToken: any;
public userJson:any;

constructor(
    private router: Router,
    private authenticationService: AuthenticationService,
    private alertService: AlertService) {

    this.userData = localStorage.getItem("currentUser");
    this.userJson = JSON.parse(this.userData);

    if(this.userJson != null) {

        this.userJson = JSON.parse(this.userData);
        this.userToken= this.userJson.token;
        alert(this.userToken);

    }



    //console.log(this.userToken.token);
}

答案 1 :(得分:0)

从我在这里可以看出来(请让我知道),你在类的构造函数中有这两个,如果是这种情况,服务可能不会在组件之前加载。

答案 2 :(得分:0)

删除module

来自l=[2,-8,9,0,-77,0,9.4,"hello","san",90,"a",(4,8,9),[8,9,9,"shree",{'a':1,'b':2,'c':[2,9,9,9.00]}]] def descend(o): if isinstance(o, (list, tuple)): for v in o: descend(v) elif isinstance(o, dict): descend(o.values()) elif isinstance(o, (int, float)): print o 并添加>>> descend(l) 2 -8 9 0 -77 0 9.4 90 4 8 9 8 9 9 1 2 9 9 9.0 2

中的所有提供商

如果在组件中添加provider [services],则这些服务将再次实例化(多个实例)