簡體   English   中英

Angular 2:數組更新后視圖不會更新

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

我有2個組件:

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() { }

}

我正在嘗試的是,從市場到集合添加項目,當它們出現在集合中時,我有一個應該刪除數據的按鈕。

更新 :執行一些日志記錄后,我發現一旦組件發生更改,該服務似乎不會保留數據(意味着從一個組件路由到另一個組件)。

請告訴我我做錯了什么。

如果在組件上提供CollectService ,則將為每個組件實例創建(並銷毀)實例。

要么在具有預期生命周期的公共父級提供它,要么使其成為全局(應用程序范圍)單例,在NgModule提供它

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM