Ali*_*ade 5 typescript angular
我正在尝试用angular 2创建一个应用程序,我的问题是如何从本地存储订阅一个项目...我知道我必须使用一个服务,只能通过这个服务从任何地方访问LocalStorage,但我不知道如何做到这一点.
Ank*_*ngh 22
对于一个基本的想法,这是如何做到的.
只需要根据您的配置编写正确的导入路径
写一个全球服务:
import {Subject} from 'rxjs/Subject';
@Injectable()
export class GlobalService {
itemValue = new Subject();
set theItem(value) {
this.itemValue.next(value); // this will make sure to tell every subscriber about the change.
localStorage.setItem('theItem', value);
}
get theItem() {
return localStorage.getItem('theItem');
}
}
Run Code Online (Sandbox Code Playgroud)
引导此服务:
bootstrap(YourApp, [GlobalService]);
Run Code Online (Sandbox Code Playgroud)
用法:
@Component({})
export class SomeComponent {
constructor(private globalSrv: GlobalService){}
someEvent() {
this.globalSrv.theItem = 'someValue'; // this change will broadcast to every subscriber like below component
}
}
Run Code Online (Sandbox Code Playgroud)
@Component({})
export class AnotherComponent {
constructor(private globalSrv: GlobalService){
globalSrv.itemValue.subscribe((nextValue) => {
alert(nextValue); // this will happen on every change
})
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7979 次 |
最近记录: |