Angular
구성 요소간에 데이터 공유
수색…
소개
이 주제의 목적은 데이터 바인딩과 공유 서비스를 통해 구성 요소간에 데이터를 공유 할 수있는 몇 가지 방법의 간단한 예제를 작성하는 것입니다.
비고
프로그래밍에서 한 가지 작업을 수행하는 방법은 항상 여러 가지가 있습니다. 현재 예제를 편집하거나 자신 만의 예제를 추가하십시오.
공유 구성 요소에서 공유 서비스를 통해 하위 구성 요소로 데이터 보내기
service.ts :
import { Injectable } from '@angular/core';
@Injectable()
export class AppState {
public mylist = [];
}
parent.component.ts :
import {Component} from '@angular/core';
import { AppState } from './shared.service';
@Component({
selector: 'parent-example',
templateUrl: 'parent.component.html',
})
export class ParentComponent {
mylistFromParent = [];
constructor(private appState: AppState){
this.appState.mylist;
}
add() {
this.appState.mylist.push({"itemName":"Something"});
}
}
parent.component.html :
<p> Parent </p>
<button (click)="add()">Add</button>
<div>
<child-component></child-component>
</div>
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>
{{mylist | json}}
`,
})
export class ChildComponent {
mylist: any;
constructor(private appState: AppState){
this.mylist = this.appState.mylist;
}
}
@Input을 사용하여 데이터 바인딩을 통해 부모 구성 요소에서 하위 구성 요소로 데이터 보내기
parent.component.ts :
import {Component} from '@angular/core';
@Component({
selector: 'parent-example',
templateUrl: 'parent.component.html',
})
export class ParentComponent {
mylistFromParent = [];
add() {
this.mylistFromParent.push({"itemName":"Something"});
}
}
parent.component.html :
<p> Parent </p>
<button (click)="add()">Add</button>
<div>
<child-component [mylistFromParent]="mylistFromParent"></child-component>
</div>
child.component.ts :
import {Component, Input } from '@angular/core';
@Component({
selector: 'child-component',
template: `
<h3>Child powered by parent</h3>
{{mylistFromParent | json}}
`,
})
export class ChildComponent {
@Input() mylistFromParent = [];
}
@Output 이벤트 이미 터를 통해 자식에서 부모로 데이터 보내기
event-emitter.component.ts
import { Component, OnInit, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'event-emitting-child-component',
template: `<div *ngFor="let item of data">
<div (click)="select(item)">
{{item.id}} = {{ item.name}}
</div>
</div>
`
})
export class EventEmitterChildComponent implements OnInit{
data;
@Output()
selected: EventEmitter<string> = new EventEmitter<string>();
ngOnInit(){
this.data = [ { "id": 1, "name": "Guy Fawkes", "rate": 25 },
{ "id": 2, "name": "Jeremy Corbyn", "rate": 20 },
{ "id": 3, "name": "Jamie James", "rate": 12 },
{ "id": 4, "name": "Phillip Wilson", "rate": 13 },
{ "id": 5, "name": "Andrew Wilson", "rate": 30 },
{ "id": 6, "name": "Adrian Bowles", "rate": 21 },
{ "id": 7, "name": "Martha Paul", "rate": 19 },
{ "id": 8, "name": "Lydia James", "rate": 14 },
{ "id": 9, "name": "Amy Pond", "rate": 22 },
{ "id": 10, "name": "Anthony Wade", "rate": 22 } ]
}
select(item) {
this.selected.emit(item);
}
}
event-receiver.component.ts :
import { Component } from '@angular/core';
@Component({
selector: 'event-receiver-parent-component',
template: `<event-emitting-child-component (selected)="itemSelected($event)">
</event-emitting-child-component>
<p *ngIf="val">Value selected</p>
<p style="background: skyblue">{{ val | json}}</p>`
})
export class EventReceiverParentComponent{
val;
itemSelected(e){
this.val = e;
}
}
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;
});
}
}
Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow