-
StackOverflow 文档
-
Angular 教程
-
在组件之间共享数据
-
使用 Observable 和 Subject 将数据从父节点异步发送到子节点
shared.service.ts:
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Observable } from 'rxjs/Observable';
import { Observable } from 'rxjs/Rx';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class AppState {
private headers = new Headers({'Content-Type': 'application/json'});
private apiUrl = 'api/data';
// Observable string source
private dataStringSource = new Subject<string>();
// Observable string stream
dataString$ = this.dataStringSource.asObservable();
constructor(private http: Http) { }
public setData(value) {
this.dataStringSource.next(value);
}
fetchFilterFields() {
console.log(this.apiUrl);
return this.http.get(this.apiUrl)
.delay(2000)
.toPromise()
.then(response => response.json().data)
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
parent.component.ts:
import {Component, OnInit} from '@angular/core';
import 'rxjs/add/operator/toPromise';
import { AppState } from './shared.service';
@Component({
selector: 'parent-component',
template: `
<h2> Parent </h2>
<h4>{{promiseMarker}}</h4>
<div>
<child-component></child-component>
</div>
`
})
export class ParentComponent implements OnInit {
promiseMarker = "";
constructor(private appState: AppState){ }
ngOnInit(){
this.getData();
}
getData(): void {
this.appState
.fetchFilterFields()
.then(data => {
// console.log(data)
this.appState.setData(data);
this.promiseMarker = "Promise has sent Data!";
});
}
}
child.component.ts:
import {Component, Input } from '@angular/core';
import { AppState } from './shared.service';
@Component({
selector: 'child-component',
template: `
<h3>Child powered by shared service</h3>
{{fields | json}}
`,
})
export class ChildComponent {
fields: any;
constructor(private appState: AppState){
// this.mylist = this.appState.get('mylist');
this.appState.dataString$.subscribe(
data => {
// console.log("Subs to child" + data);
this.fields = data;
});
}
}