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

时间:2017-04-22 09:44:23

标签: javascript angular typescript angular-services

我想做一个待办事项列表,我有两个组件(以后更多) 我会分享一组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:我更容易接受其他解决方案

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

this.tacheService.insert(name)

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

taches: Tache[] = [];

将该实例变量放在服务上。然后,直接从服务访问该变量(eh)或在返回它的服务上实现一个函数(更好)。

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