How can i import angular-2-local-storage in my angular 2 app (angular-cli)

1.1k Views Asked by At

How can I import angular-2-local-storage in my angular 2 app, I am using the angular-cli generator. Floder stucture

enter image description here

angular-2-local-storage in node_module folder. I want to use it in my component. I am tryed this code

import { LocalStorageService } from '../../../node_modules/angular-2-local-storage';

constructor(
        private localStorageService: LocalStorageService
    ) { }

But getting this error

enter image description here

1

There are 1 best solutions below

0
On

For starters store.js is a fanatic library if that is the route you are looking to go. It supports typescript and if you are using the angular-cli and npm it is extremely easy to set up.

DefinitelyType is a collection of type script definition files that can be added to the project to provide strong typings for external libraries that may otherwise prove to be challenging to build in.

Once added, the angular cli will automatically included the dependencies in your project. (Located in npm_modules with an @prefix) To use these libraries all just import a reference and you are basically good to go. In some ways they can be used that same way as an angular 2 library.

Route 2 is also fairly simple for local storage, below is a snippet from a sandbox app. This makes use of the localStorage in a service.

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';

@Injectable()
export class UserService {
  private loggedIn = false;

  constructor(private http: Http) {
    this.loggedIn = !!localStorage.getItem('auth_token');
  }

  login(email, password) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    let self = this;
    return new Promise(function (resolve, reject) {
      if (email === '[email protected]' && password === 'test') {
        localStorage.setItem('auth_token', 'xyz');
        self.loggedIn = true;
        resolve(true);
      } else {
        resolve(false);
      }
    });
  }

  setPassword(password) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    let self = this;
    return new Promise(function (resolve, reject) {
      resolve(true);
    });
  }

  logout() {
    localStorage.removeItem('auth_token');
    this.loggedIn = false;
  }

  isLoggedIn() {
    return this.loggedIn;
  }
}