localStorage 未定义(Angular Universal) [英] localStorage is not defined (Angular Universal)

查看:50
本文介绍了localStorage 未定义(Angular Universal)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用

顺便说一句,我发现了一个 import { LocalStorage } from 'angular2-universal';,但不知道如何使用它.

<小时>

UPDATE 2,我改成(不知道有没有更好的方法):

import { Injectable, Inject } from '@angular/core';从'@angular/http' 导入 { Http };从'../../local-storage'导入{LocalStorage};@Injectable()导出类 UserService {构造函数(私有_http: Http,@Inject(LocalStorage) private localStorage) {}//<- 这一行是新的加载当前用户(){const token = this.localStorage.getItem('token');//这里我从`localStorage` 改为`this.localStorage`//...};}

这解决了 UPADAT 1 中的问题,但现在我在终端中出现错误:

<块引用>

例外:类型错误:this.localStorage.getItem 不是函数

解决方案

更新 Angular 的新版本

OpaqueTokenInjectionToken 取代,它的工作方式大致相同——除了它有一个通用接口 InjectionToken为了更好的类型检查和推理.

原始答案

两件事:

  1. 您没有注入任何包含 localStorage 对象的对象,而是尝试将其作为全局对象直接访问.任何全局访问都应该是出现问题的第一个线索.
  2. nodejs 中没有 window.localStorage.

您需要做的是为 localStorage 注入一个适用于浏览器和 NodeJS 的适配器.这也将为您提供可测试的代码.

在 local-storage.ts 中:

import { OpaqueToken } from '@angular/core';export const LocalStorage = new OpaqueToken('localStorage');

在您的 main.browser.ts 中,我们将从您的浏览器注入实际的 localStorage 对象:

import {LocalStorage} from './local-storage.ts';导出函数 ngApp() {返回引导程序(应用程序,[//...用户服务,{ 提供:LocalStorage,useValue:window.localStorage}]);

然后在 main.node.ts 中我们将使用一个空对象:

<代码>...提供者:[//...用户服务,{提供:LocalStorage,useValue:{getItem() {}}}]...

然后你的服务注入这个:

import { LocalStorage } from '../local-storage';导出类 UserService {构造函数(@Inject(LocalStorage)私有localStorage:LocalStorage){}加载当前用户(){const token = this.localStorage.getItem('token');...};}

I am using universal-starter as backbone.

When my client starts, it read a token about user info from localStorage.

@Injectable()
export class UserService {
  foo() {}

  bar() {}

  loadCurrentUser() {
    const token = localStorage.getItem('token');

    // do other things
  };
}

Everything works well, however I got this in the server side (terminal) because of server rendering:

EXCEPTION: ReferenceError: localStorage is not defined

I got the idea from ng-conf-2016-universal-patterns that using Dependency Injection to solve this. But that demo is really old.

Say I have these two files now:

main.broswer.ts

export function ngApp() {
  return bootstrap(App, [
    // ...

    UserService
  ]);
}

main.node.ts

export function ngApp(req, res) {
  const config: ExpressEngineConfig = {
    // ...
    providers: [
      // ...
      UserService
    ]
  };

  res.render('index', config);
}

Right now they use both same UserService. Can someone give some codes to explain how to use different Dependency Injection to solve this?

If there is another better way rather than Dependency Injection, that will be cool too.


UPDATE 1 I am using Angular 2 RC4, I tried @Martin's way. But even I import it, it still gives me error in the terminal below:

Terminal (npm start)

/my-project/node_modules/@angular/core/src/di/reflective_provider.js:240 throw new reflective_exceptions_1.NoAnnotationError(typeOrFunc, params); ^ Error: Cannot resolve all parameters for 'UserService'(Http, ?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'UserService' is decorated with Injectable.

Terminal (npm run watch)

error TS2304: Cannot find name 'LocalStorage'.

I guess it is somehow duplicated with the LocalStorage from angular2-universal (although I am not using import { LocalStorage } from 'angular2-universal';), but even I tried to change mine to LocalStorage2, still not work.

And in the meanwhile, my IDE WebStorm also shows red:

BTW, I found a import { LocalStorage } from 'angular2-universal';, but not sure how to use that.


UPDATE 2, I changed to (not sure whether there is a better way):

import { Injectable, Inject } from '@angular/core';
import { Http } from '@angular/http';
import { LocalStorage } from '../../local-storage';

@Injectable()
export class UserService {
  constructor (
    private _http: Http,
    @Inject(LocalStorage) private localStorage) {}  // <- this line is new

  loadCurrentUser() {
    const token = this.localStorage.getItem('token'); // here I change from `localStorage` to `this.localStorage`

    // …
  };
}

This solves the issue in UPADAT 1, but now I got error in the terminal:

EXCEPTION: TypeError: this.localStorage.getItem is not a function

解决方案

Update for newer versions of Angular

OpaqueToken was superseded by InjectionToken which works much in the same way -- except it has a generic interface InjectionToken<T> which makes for better type checking and inference.

Orginal Answer

Two things:

  1. You are not injecting any object that contains the localStorage object, you are trying to access it directly as a global. Any global access should be the first clue that something is wrong.
  2. There is no window.localStorage in nodejs.

What you need to do is inject an adapter for localStorage that will work for both the browser and NodeJS. This will also give you testable code.

in local-storage.ts:

import { OpaqueToken } from '@angular/core';

export const LocalStorage = new OpaqueToken('localStorage');

In your main.browser.ts we will inject the actual localStorage object from your browser:

import {LocalStorage} from './local-storage.ts';

export function ngApp() {
  return bootstrap(App, [
    // ...

    UserService,
    { provide: LocalStorage, useValue: window.localStorage}
  ]);

And then in main.node.ts we will use an empty object:

... 
providers: [
    // ...
    UserService,
    {provide: LocalStorage, useValue: {getItem() {} }}
]
...

Then your service injects this:

import { LocalStorage } from '../local-storage';

export class UserService {

    constructor(@Inject(LocalStorage) private localStorage: LocalStorage) {}

    loadCurrentUser() {

        const token = this.localStorage.getItem('token');
        ...
    };
}

这篇关于localStorage 未定义(Angular Universal)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆