简体   繁体   English

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

[英]Angular 2 : View doesn`t update after array is updated

I have 2 components : 我有2个组件:

collection.component.ts 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 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 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 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 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() { }

}

What I am trying is, is to add items from market to collection and when they appear in the collection, I have a button which should be removing the data. 我正在尝试的是,从市场到集合添加项目,当它们出现在集合中时,我有一个应该删除数据的按钮。

Update : After doing some logging, I found that the service doesn`t seem to retain the data once component changes (means routing from one component to another). 更新 :执行一些日志记录后,我发现一旦组件发生更改,该服务似乎不会保留数据(意味着从一个组件路由到另一个组件)。

Please advice what I am doing wrong. 请告诉我我做错了什么。

If you provide CollectService on the component, an instance will be created (and destroyed) with each component instance. 如果在组件上提供CollectService ,则将为每个组件实例创建(并销毁)实例。

Either provide it at a common parent that has the expected lifetime, or to make it a global (application-wide) singleton, provide it in NgModule 要么在具有预期生命周期的公共父级提供它,要么使其成为全局(应用程序范围)单例,在NgModule提供它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM