[英]Angular 2, How to Share Array Data Between components using service?
[英]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.