Nectar Mind
Nectar Mind

Reputation: 145

How to get local storage data in service/component angular 2

I am new to angular2 and trying to save the data in local storage after login and its working fine for me and I am able to get that item from local storage in same service but there is an issue to get that local storage in other services/components. Here is my code.

I have set the value in login.service but unable to get in login component. Please see if any can help me out.

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

Upvotes: 1

Views: 9301

Answers (3)

Nectar Mind
Nectar Mind

Reputation: 145

Yes its working now. Actually we have to define global variable and store the local storage data in that variable. Now further we can use it anywhere in component. Thanks.

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

Upvotes: 4

anshuVersatile
anshuVersatile

Reputation: 2068

remove providers:[AlertService, AuthenticationService]

from your login.component.ts and add all providers in module

if you add provider[services] in component then these services will instantiate again (multiple instance)

Upvotes: 0

Tucker
Tucker

Reputation: 1932

From what I can tell here (please let me know otherwise) you have both of these in the constructor of the classes, if that is the case, the service may not be loaded before the component.

Upvotes: 0

Related Questions