简体   繁体   中英

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

在此输入图像描述

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 localStorage@1.0.3 instaled.

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM