繁体   English   中英

如何在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)或在返回它的服务上实现一个函数(更好)。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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