是否有办法将组件中的局部变量(模型)与localstorage项绑定。
例如当某个项user
从localStorage
中移除时,我的组件的模型变量会自动变空,反之亦然。
答案 0 :(得分:1)
您可以创建用户服务和可观察对象以保持所有组件的更新
import { Injectable } from '@angular/core';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class StorageService {
usersChanged = new Subject<string[]>();
users: string[] = [];
constructor() { }
addUser(user: string) {
this.users.push(user);
this.usersChanged.next(this.users);
}
remove(index: number) {
this.users.splice(index, 1);
this.usersChanged.next(this.users);
}
getUsers() {
return this.users.slice();
}
}
然后在您的每个依赖组件中,您可以订阅任何更改
users: string[] = this.storageService.getUsers();
constructor(private storageService: StorageService) {}
ngOnInit() {
this.storageService.usersChanged
.subscribe( (users ) => this.users = users);
}