我正在尝试使用 Angular 2 创建一个应用程序,我的问题是如何从本地存储订阅一个项目...我知道我必须使用一项服务,只能通过该服务从任何地方访问 LocalStorage,但我不知道不知道如何做到这一点。
最佳答案
对于一个基本的想法,这是如何完成的。
只需要根据您的配置编写正确的导入路径
编写全局服务:
import {BehaviorSubject} from 'rxjs';
@Injectable({providedIn: 'root'})
export class GlobalService {
itemValue = new BehaviorSubject(this.theItem);
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');
}
}
用法:
- 此处的任何更改
@Component({})
export class SomeComponent {
constructor(private globalSrv: GlobalService){}
someEvent() {
this.globalSrv.theItem = 'someValue'; // this change will broadcast to every subscriber like below component
}
}
- 会在这里反射(reflect)
@Component({})
export class AnotherComponent {
constructor(private globalSrv: GlobalService){
globalSrv.itemValue.subscribe((nextValue) => {
alert(nextValue); // this will happen on every change
})
}
}
关于angular - 如何在 Angular 2 中从本地存储订阅项目并在更改时获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37541783/