如何在 Angular 2 中的组件之间共享一个数组?

How to share an array between components in Angular 2?

我想列一个待办事项清单,我有 2 个组成部分(以后还会有更多) 我会分享一个数组 Tache .

导航栏组件

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 组件

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);
  }
}

服务

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 组件未完成,我将在它们中使用函数 insert 来传递数据并将其保存在服务中声明的 taches 数组中(以便所有组件都可以访问数据) 我收到一个错误:

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

PS: 如果更简单,我接受其他解决方案

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

在第 26 行,您应该这样做:

this.tacheService.insert(name)

您的所有组件都需要访问同一个 Tache[]?在这种情况下,最简洁的实现方式是在需要时直接从服务中获取该值。因此,不是将 taches 存储为组件上的实例变量:

taches: Tache[] = [];

改为将该实例变量放在服务上。然后,要么直接从服务访问该变量 (eh),要么在服务上实现 returns 它(更好)的功能。

如果您出于某种原因绝对必须将 Tache[] 存储在组件中,则另一种选择是让 tache 服务公开 Tache[] 订阅并让所有组件订阅它。参见 http://blog.angular-university.io/how-to-build-angular2-apps-using-rxjs-observable-data-services-pitfalls-to-avoid/