2017-01-02 19 views
3

有一个不错的q &一个在这里会使用localStorage和angular2。 https://stackoverflow.com/a/39098748/6203604角通用启动,localStorage的生产中:在browser.module使用“窗口”指本地存储中断生产建设

这种做法似乎好工作与“新公共管理的开始”。然而,当你运行“故宫运行生成”错误:

Property 'window' does not exist on type 'typeof ../browser.module' appears.

在“通用陷阱”上https://github.com/angular/universal-starter它说

window, document, navigator, and other browser types - do not exist on the server - so using them, or any library that uses them (jQuery for example) will not work. You do have some options, if you truly need some of this functionality: If you need to use them, consider limiting them to only your main.client and wrapping them situationally with the imported isBrowser/isNode features from Universal. import { isBrowser, isNode } from 'angular2-universal'; Another option is using DOM from "@angular/platform-browser"

会的isBrowser包装或使用该平台的浏览器适合在这里指localStorage的?任何如何最好的写这个例子?

e.g在browser.module.ts,是有什么事应该做包装window.localStorage的分配管束?

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

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

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

有些事情要与'npm run build'可分发的捆绑包一起使用吗?

此外,运行NPM开始的时候,我得到错误信息:意外的令牌ü。 enter image description here

这似乎来自文件node.module.ts中useValue中的'u',因为disapears并被替换为'没有Token LocalStorage提供程序!'

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

任何人都得到类似的东西。想法?

回答

0

您可以使用“假”存储服务来访问不实际访问的服务器window,并使用DI将其设置在服务器模块上,并且右侧的window可访问浏览器模块。一个很好的例子可以发现here

+0

感谢伊萨克,我给它一个去这个周末,让你知道如何去。 – owenc