简体   繁体   中英

How to share an array between components in Angular 2?

I would like to make a to-do list , I have 2 components ( and more later ) I would share an array of Tache .

Navbar Component

import { Component } from '@angular/core';
import { Router } from '@angular/router';

import { Tache } from './tache';
import { TacheService } from './tache.service';
import { InMemoryDataService } from './en-memoire';
@Component({
  selector: 'navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavBarComponent {
  constructor(
    private tacheService: TacheService) {}

  add(name: string): void {
    name = name.trim();
    if (!name) {return;}
    this.tacheService.create(name)
      .then(tache => {
        return insert(tache);
      });
  }
}

TachesInit Component

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { Tache } from './tache';
import { TacheService } from './tache.service';
import { InMemoryDataService } from './en-memoire';

@Component({
  selector: 'tachesInit',
  templateUrl: './tachesInit.component.html',
  styleUrls: ['./tachesInit.component.css']
})
export class TachesInitComponent implements OnInit {

  tacheSelectionnee: Tache;
  constructor(
    private tacheService: TacheService) {}
  ngOnInit(): void {
    this.tacheService.getTaches()
      .then(taches => this.taches = taches);
  }
}

Service

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';

import { Tache } from './tache';

@Injectable()
export class TacheService {
  private headers = new Headers({'Content-Type': 'application/json'});
  private tachesUrl = 'api/taches';  // URL to web api
  taches: Tache[] = [];

  tacheSelectionnee: Tache;

  constructor(private http: Http) {}
  getTaches(): Promise<Tache[]> {
    return this.http.get(this.tachesUrl)
      .toPromise()
      .then(response => {
        let taches = response.json().data as Tache[];
        console.log(taches);
        return taches;
      })
      .catch(this.handleError);
  }

  create(name: string): Promise<Tache> {
    return this.http
      .post(this.tachesUrl, JSON.stringify({name: name, stat: 0}), {headers: this.headers})
      .toPromise()
      .then(res => res.json().data as Tache)
      .catch(this.handleError);
  }

  insert(tache: Tache): void {
    this.taches.push(tache);
  }
}

TachesInit Component in not finished, I would use the function insert in both of them to pass the data and save it in taches array declared in the service ( so that all the components could access to the data ) I get an error :

src/app/navbar.component.ts(26,15): error TS2304: Cannot find name 'insert'

PS: I accept other solutions if easier

组件必须是无状态的,所有状态都存储在服务中。

On line 26, you should be doing:

this.tacheService.insert(name)

All of your components need access to the same Tache[]? In this case, the cleanest way to implement it would be to get that value directly from the service when it's needed. So instead of storing taches as an instance variable on the component:

taches: Tache[] = [];

Put that instance variable on the service instead. Then, either access that variable from the service directly (eh) or implement a function on the service that returns it (better).

Another option, if you absolutely have to store the Tache[] in the components for some reason, would be to have the tache service expose a Tache[] subscription and have all of the components subscribe to it. See http://blog.angular-university.io/how-to-build-angular2-apps-using-rxjs-observable-data-services-pitfalls-to-avoid/ .

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