简体   繁体   English

将localStorage包装在angular2服务中?

[英]Wrapping localStorage in a angular2 service?

Is it wise to wrap the local storage in a service in angular2. 将本地存储包装在angular2中的服务中是否明智。 Are there any arguments why this should be done like that. 是否有任何争论为什么要这样做? Obviously it is much neater. 显然,它更加整洁。 Calling the service as a dependency injection on a component. 调用服务作为对组件的依赖项注入。 I don't see any other "pros" on that. 我看不到其他“优点”。

For example (local storage in a service) 例如(服务中的本地存储)

setHost(value: string) {
    localStorage.setItem(STATIC_VARIABLE_KEY, value);
  }

  getHost(): string {
    return localStorage.getItem(STATIC_VARIABLE_KEY);
  }

Well the main reason why it is good idea is that there are still browsers, that does not support localStorage when in private mode, and by using this layer of abstraction, you can simply replace localStorage with cookie , when it's not available. 好主意的主要原因是,仍然有一些浏览器在私有模式下不支持localStorage ,并且通过使用这一抽象层,您可以在cookie不可用时简单地将localStorage替换为cookie

For example even MacOS safari in incognito mode was not supporting it until latest High Sierra release. 例如,直到隐身模式下的MacOS Safari才支持最新的High Sierra版本。 Mobile Safari has this problem also. 移动Safari也存在此问题。 (I think it's still there on iOS 11, not sure tho.) (我认为它在iOS 11上仍然存在,不确定。)

But I would suggest using some ready made solution, instead of doing it from scratch. 但是我建议您使用一些现成的解决方案,而不是从头开始。 Take a look at this module: 看一下这个模块:

https://github.com/phenomnomnominal/angular-2-local-storage https://github.com/phenomnomnominal/angular-2-local-storage

Another reason for doing this could be compatibility with server side rendering (via angular/universal) as localStorage is not available on server side at all. 这样做的另一个原因可能是与服务器端渲染(通过角度/通用)兼容,因为localStorage在服务器端根本不可用。

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

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