具有localstorage的Angular 5绑定模型

时间:2018-01-11 19:07:35

标签: angular

是否有办法将组件中的局部变量(模型)与localstorage项绑定。

例如当某个项userlocalStorage中移除时,我的组件的模型变量会自动变空,反之亦然。

1 个答案:

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