简体   繁体   中英

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

I have 2 components :

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

}

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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