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

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

问题描述

我正在使用 universal-starter 作为主干.

我的客户端启动时,它从localStorage读取有关用户信息的令牌.

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:

例外:ReferenceError:未定义localStorage

EXCEPTION: ReferenceError: localStorage is not defined

我从 ng中得到了这个想法-conf-2016-universal-patterns 使用依赖注入解决此问题.但是那个演示真的很老.

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

说我现在有两个文件:

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);
}

现在,他们两个都使用相同的UserService.有人可以给一些代码解释如何使用不同的依赖注入来解决这个问题吗?

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.

更新1 我正在使用Angular 2 RC4,尝试了@Martin的方法.但是,即使我导入了它,也仍然在下面的终端中给我错误:

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:

终端(npm开始)

/my-project/node_modules/@angular/core/src/di/reflective_provider.js:240 抛出新的reflective_exceptions_1.NoAnnotationError(typeOrFunc,params); ^错误:无法解析'UserService'(Http,?)的所有参数.确保所有参数都用注入"或修饰"修饰. 具有有效的类型批注,并且"UserService"使用修饰符 可注射的.

/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.

终端(npm运行监视)

错误TS2304:找不到名称"LocalStorage".

error TS2304: Cannot find name 'LocalStorage'.

我想它与angular2-universal中的LocalStorage有某种相似之处(尽管我没有使用import { LocalStorage } from 'angular2-universal';),但是即使我尝试将我的名称更改为LocalStorage2,仍然无法正常工作.

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.

与此同时,我的IDE WebStorm也显示红色:

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

顺便说一句,我找到了import { LocalStorage } from 'angular2-universal';,但不确定如何使用它.

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

更新2 ,我改为(不确定是否有更好的方法):

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`

    // …
  };
}

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

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

例外:TypeError:this.localStorage.getItem不是函数

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

推荐答案

更新了Angular的较新版本

OpaqueTokenInjectionToken取代,后者的工作方式大致相同-但它具有通用接口InjectionToken<T>,可以更好地进行类型检查和推断.

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.

原始答案

两件事:

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

您需要做的是为localStorage注入一个适配器,该适配器将同时适用于浏览器和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.

在local-storage.ts中:

in local-storage.ts:

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

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

在您的main.browser.ts中,我们将从您的浏览器中注入实际的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}
  ]);

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

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天全站免登陆