Angular 5 将模型与本地存储绑定



有没有办法将组件中的局部变量(模型(与本地存储项绑定。

例如,当从localStorage中删除项目user时,我的组件的模型变量会自动变为空,反之亦然。

您可以创建用户服务和可观察量以保持所有组件的更新

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);
  }

最新更新