Lea
Lea

Reputation: 1285

Angular2 Trying to use localStorage globally but does not work?

Hi I am using localStorage in Angular2.

To check if the user is logged in, I tried to call this

        this.currentUser = JSON.parse(localStorage.getItem('currentUser'));

in every component but since this should be called in every component,

I decided to make it global so I created service

import { Injectable } from '@angular/core';

import { User } from '../../model/auth_user';

import { HttpClient } from '../HttpClient';


@Injectable()
export class LoginCheckService {

constructor(private http: HttpClient) { }

LoginCheck(currentUser: User) {
    currentUser = JSON.parse(localStorage.getItem('currentUser')); //to check if the user is logged in
    if (currentUser == null) {
        console.log('hello!') //just to check if the currentUser is null the 'get' method gets called, however, hello! is printed but i can't seem to track any request done. 
        this.http.get('/front/member/session');
        }
    }
}

Like this and in main component, I did this.

  currentUser: User;

  constructor(private auth: AuthenticationService,
    private router: Router,
    private loginCheck: LoginCheckService) {
    this.loginCheck.LoginCheck(this.currentUser);
  }

However, even when I am logged in, the currentUser from the main component still seems to be empty which did not happen previously when I wasnt using service.

And I also added if statement so if the currentUser is null I have to send 'get' http request but this is also not requested.

What am I doing wrong?

Thank you.

(I added service to provider)

Upvotes: 0

Views: 49

Answers (2)

Aleksey Temnov
Aleksey Temnov

Reputation: 96

I don't see a place in your code where you are setting anything to your localStorage currentUser parameter.

Does your HttpClient.get returnes an Observable? If so you need to subscribe in order to initiate http request.

this.http.get('/front/member/session').subscribe(result => {
    // do something with result
    // save it to localstorage, i guess
});

Upvotes: 1

user4676340
user4676340

Reputation:

Because you are missing a lot of code.

In your service, you made a function with a currentUser. Then, immediately, you change its value to your localStorage value (currentUser = JSON.parse(...)).

This is all you do. You should add some more code so that it does some more.

For instance :

component

constructor(/* imports */) {
    this.currentUser = this.loginCheck.LoginCheck();
}

service

LoginCheck(): any {
    return JSON.parse(/* your localStorage value */);
}

Upvotes: 1

Related Questions