【问题标题】:How can i import angular-2-local-storage in my angular 2 app (angular-cli)如何在我的 angular 2 应用程序(angular-cli)中导入 angular-2-local-storage
【发布时间】:2016-12-22 14:51:15
【问题描述】:

如何在我的 Angular 2 应用程序中导入 angular-2-local-storage,我正在使用 angular-cli 生成器。 弗洛德结构

angular-2-local-storage 在 node_module 文件夹中。我想在我的组件中使用它。我试过这段代码

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

constructor(
        private localStorageService: LocalStorageService
    ) { }

但出现此错误

【问题讨论】:

  • 为什么需要本地存储库,而本地代码只有 1 行来获取和设置数据?

标签: angular typescript node-modules


【解决方案1】:

对于初学者来说,store.js 是一个狂热的图书馆,如果那是你想要走的路。它支持打字稿,如果您使用 angular-cli 和 npm,它非常容易设置。

DefinitelyType 是类型脚本定义文件的集合,可以添加到项目中以为外部库提供强类型化,否则这些库可能难以构建。

添加后,Angular cli 将自动将依赖项包含在您的项目中。 (位于带有@prefix 的npm_modules 中)要使用这些库,只需导入一个引用,您基本上就可以开始使用了。在某些方面,它们的使用方式与 Angular 2 库相同。

Route 2 对于本地存储也相当简单,下面是来自沙盒应用程序的 sn-p。这利用了服务中的 localStorage。

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 === 'test@test.com' && 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;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 2017-11-16
    • 2017-11-01
    • 1970-01-01
    • 2016-09-02
    • 2017-03-01
    相关资源
    最近更新 更多