Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 dependency not injecting correct path

I am getting the following errors in my browser console, from trying to use localStorage with Angular2. It seems that the path it is generating isn't referring to the node_modules, but rather assuming that there is a localstorage.js in my site root (which there isn't). I am just referring to it normally (see my user.service below), so how do I get around this? All my other dependencies are working fine.

Error loading http://localhost:3000/localStorage.js as "localStorage" from http://localhost:3000/client/dev/user/services/user.service.js

enter image description here

import { Injectable } from 'angular2/core';
import { Headers } from 'angular2/http';
import { loalStorage } from 'localStorage';

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

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

}

NB: I am fairly sure there isn't an actual problem with the localStorage installation, as if I run npm list localStorage, then it tells me I have [email protected] instaled.

like image 621
George Edwards Avatar asked Aug 12 '26 02:08

George Edwards


1 Answers

If you want to use localStorage from an import, you need to configure it within SystemJS as described below:

System.config({
  map: {
    localStorage: 'node_modules/localStorage/lib/localStorage.js'
  },
  (...)
});

This way, you will be able to use the following import:

import loalStorage from 'localStorage';

See this question for more details since it's similar to the way to configure Lodash:

  • Lodash in angular2, declare var_:any not working
like image 166
Thierry Templier Avatar answered Aug 13 '26 16:08

Thierry Templier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!