简体   繁体   English

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

[英]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 . 我想做一个待办事项列表,我有2个组件(以后更多)我将共享一个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 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);
  }
}

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

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

PS: I accept other solutions if easier PS:我更容易接受其他解决方案

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

On line 26, you should be doing: 在第26行,您应该这样做:

this.tacheService.insert(name)

All of your components need access to the same Tache[]? 您的所有组件都需要访问相同的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作为实例变量存储在组件上:

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). 然后,直接从服务访问该变量(eh)或在返回它的服务上实现一个函数(更好)。

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