Angular 2:如何在服务中创建一个组件将观察到更改的数组?

时间:2016-05-18 20:37:59

标签: service typescript angular observable ionic2

我希望我的NotificationsBellComponent接收服务中数组的更改。假设_LocalStorageService正在正确发送数据。

问:如何让我的组件在服务收集发生时接收更改?

到目前为止的组件:

@Component({
    selector: 'notifications-bell',
    directives: [],
    templateUrl: 'build/components/notificationsBell/notificationsBell.html',
    styles: [`
        button{
            background: none !important;
            background-color: none !important;
            box-shadow: none !important;
        }
    `]
})
export class NotificationsBellComponent {

    private notifications: string[];

    constructor(
        private _platform: Platform,
        private _nav: NavController,
        private _events: Events,
        private _ConfigService: ConfigurationService,
        private _NotificationService: NotificationService
    ) {
        this.notifications = this._NotificationService.notifications;
    }
}

到目前为止的服务:

@Injectable()
export class NotificationService {

  public notifications: string[];

  constructor(
    private _ConfigService: ConfigurationService,
    private _LocalStorageService: LocalStorageService,
    private _I8nService: I8nService,
    private _events: Events
  ) {
    this.getData();
  }

  getData() {
    this._LocalStorageService.getNotifications().then((data) => {
      var list: string[] = [];
      if (data.res.rows.length > 0) {
        for (var i = 0; i < data.res.rows.length; i++) {
          list.push(data.res.rows.item(i).notification);
        }
      }
      this.notifications = list;
    });
  }

  addItem(description: string) {
    this._LocalStorageService.addNotification(description).then(() => {
      this.getData();
    });
  }
}

2 个答案:

答案 0 :(得分:1)

每次承诺结算时,

getData()会将notifications分配给新的list数组。您的组件仍将引用原始list数组。

不是每次都分配一个新数组,而是清除它并将push()新数据放到它上面:

export class NotificationService {
  public notifications: string[];
  getData() {
    this._LocalStorageService.getNotifications().then((data) => {
      this.notifications.length = 0;  // clear array, but keep same reference
      if (data.res.rows.length > 0) {
        for (var i = 0; i < data.res.rows.length; i++) {
          this.notifications.push(data.res.rows.item(i).notification);
        }
      }
    });
  }
  ...
}

答案 1 :(得分:0)

不在服务中创建数组。

这样做,你就可以打破链条#34;这个可观察序列:你想要在你的组件中有一个observable,你(显然)从你的LocalStorageService获得一个observable,所以你的目标应该是将它建模为一个流而不是破坏它在您的服务中。

类似的东西:

@Injectable()
export class NotificationService {

  public notifications$: Observable<string[]>;

   constructor(
     private _ConfigService: ConfigurationService,
     private _LocalStorageService: LocalStorageService,
     private _I8nService: I8nService,
     private _events: Events
   ) {
      this.notifications$ = this._LocalStorageService.getNotifications()
          .map(notifications => {
              // modify the notifications however you need to her
          }) 

   }
}

然后,在您的服务中,您可以subscribe()service.notifications$