简体   繁体   English

Angular2依赖项没有注入正确的路径

[英]Angular2 dependency not injecting correct path

I am getting the following errors in my browser console, from trying to use localStorage with Angular2. 我在浏览器控制台中遇到以下错误,尝试将localStorage与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). 它似乎生成的路径似乎不是指node_modules,而是假设我的站点根目录中存在localstorage.js(没有)。 I am just referring to it normally (see my user.service below), so how do I get around this? 我只是正常提到它(请参阅下面的user.service),那么我该如何解决这个问题呢? 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 http:// localhost:3000 / client / dev / user / services / user.service.js加载http:// localhost:3000 / localStorage.js为“localStorage”时出错

在此输入图像描述

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. 注意:我很确定localStorage安装没有实际问题,好像我运行npm list localStorage ,然后它告诉我我有localStorage@1.0.3 instaled。

If you want to use localStorage from an import, you need to configure it within SystemJS as described below: 如果要从导入中使用localStorage,则需要在SystemJS中对其进行配置,如下所述:

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的方式类似:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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