Angular 2:数组更新后视图不会更新

时间:2017-04-10 07:27:31

标签: angular typescript

我有两个组成部分:

collection.component.ts

import { Component, OnInit } from '@angular/core';
import { CollectService } from '../collect.service';
import { Collectable } from '../collectable.model';
import {Observable} from 'rxjs/Rx';

@Component({
  selector: 'app-collection',
  templateUrl: './collection.component.html',
  styleUrls: ['./collection.component.css'],
  providers: [CollectService]
})
export class CollectionComponent implements OnInit {

  market: Collectable[] = [];
  constructor(private _collectService: CollectService) { }

  ngOnInit():any {
    this._collectService.getMarket().then((collectable: Collectable[]) => {this.market = collectable});
  }

  remove(item: Collectable) {
    this._collectService.removeFromMarket(item);
  }

}

collection.component.html

<div class="row">
  <div class="col-xs-12">
    <ul class="list-group" *ngIf="market.length > 0">
      <li class="list-group-item" *ngFor="let item of market">
        <span class="badge">{{item.name}}</span>&nbsp;
        <button class="btn btn-danger" (click)="remove(item)">Remove from Collection</button>
        {{item.desc}}
      </li>
    </ul>
    <h3 *ngIf="market.length === 0">Start adding items first!</h3>
  </div>
</div>

market.component.ts

import { Component, OnInit } from '@angular/core';
import { CollectService } from '../collect.service';
import { Collectable } from '../collectable.model';
@Component({
  selector: 'app-market',
  templateUrl: './market.component.html',
  styleUrls: ['./market.component.css'],
  providers: [ CollectService ]
})
export class MarketComponent implements OnInit {

  array: Collectable[] = [];  

  add(item) {
    this._collectService.addToMarket(item);
  }

  constructor(private _collectService: CollectService) { }

  ngOnInit() {
    this.array = this._collectService.getCollectable();
  }

}

market.component.html

<div class="row">
  <div class="col-xs-12">
    <ul class="list-group">
      <li class="list-group-item" *ngFor="let item of array">
        <span class="badge">{{item.name}}</span>&nbsp;
        <button class="btn btn-success" (click)="add(item)">Add to Collection</button>
        {{item.desc}}
      </li>
    </ul>
  </div>
</div>

contact.service.ts

import { Injectable } from '@angular/core';
import { Collectable } from './collectable.model';
@Injectable()
export class CollectService {

  private array: Collectable[] = [
    new Collectable ('jQuery', 'A good framework!'),
    {name: 'HTML', desc: 'A basic for web development!'},
    {name: 'CSS', desc: 'A styling weapon!'},
    {name: 'BootStrap', desc: 'A styling framework!'},
    {name: 'Angular', desc: 'A SPA framework!'},
    {name: 'React', desc: 'A SPA library!'},
    {name: 'Redux', desc: 'Go find yourself!'},
  ];

  private market: Collectable[] = [];

  public getCollectable() {
    return this.array;
  }

  public getMarket() {
    return Promise.resolve(this.market);
  }

  addToMarket(item: Collectable) {
    if (this.market.indexOf(item) == -1) {
      Promise.resolve(this.market).then((collection: Collectable[])=>{
        this.market.push(item);
      });
      // console.log('Added item : ' + item.name + ' Desc : ' + item.desc);
    }
    console.log("Array entries : ");
    for(let item2 of this.market){
      console.log('Added item : ' + item2.name + ' Desc : ' + item2.desc);
    }
  }

  removeFromMarket(item: Collectable) {
    this.market.splice(this.market.indexOf(item), 1);
  }
  constructor() { }

}

我正在尝试的是,从市场到集合中添加项目,当它们出现在集合中时,我有一个应该删除数据的按钮。

更新:在做了一些日志记录后,我发现一旦组件发生变化,服务似乎不会保留数据(意味着从一个组件路由到另一个组件)。

请告知我的错误。

1 个答案:

答案 0 :(得分:3)

如果在组件上提供CollectService,则将为每个组件实例创建(并销毁)实例。

在具有预期生命周期的公共父级中提供它,或者使其成为全局(应用程序范围)单例,在NgModule

中提供它
@NgModel({
  providers: [CollectService],
  ...
})
export class AppModule {}