Angular2 - 数据共享与数据传递 - 组件(component/pipe/directive)之间数据传递
1. 给pipe输入参数,改通道根据参数返回不同的值
Angular2 - Starter - Pipes, Custom Pipes
2. Output/Input
如下构造一个people-resolver 指令,改指令根据输入的user,去查找该user的详细信息,并发送给people-finder.
//people-resolver.directive.ts
import { Component, Directive, ElementRef, Renderer,Input,Output,EventEmitter } from '@angular/core'; import { User } from '../../../../models/business/User'; import { PeopleSvc } from '../../../../services/people.service'; import set = Reflect.set; /* * Directive * XLarge is a simple directive to show how one is made */ @Directive({ //该指令使用标签方式<people-resolver></people-resolver> selector: 'people-resolver', }) export class PeopleResolver{ private peopleSvc:PeopleSvc; public selectedPersonId:string; private element:ElementRef; //定义输入属性selectedPerson @Input() selectedPerson:User; //发现输入属性的引用变化时,更新当前选中的user,同时异步去获取用户详细信息 @Input('selectedPerson') set updateSelected(person:User){ if(person !== null){ this.selectedPerson = person; this.getUserIdAsync(this.selectedPerson['name']); } } /*定义输出事件,通过给(changeSelectedPerson)='doSomething($event)' 来传递数据,changeSelectedPerson是一个emitter,即事件发送器;我们将改发送器的发送数据类型设为string. */ //Output 装饰的属性,一般为一个事件发送器 @Output() changeSelectedPerson:EventEmitter<string> = new EventEmitter(); //异步获取用户的Id getUserIdAsync(name){ this.element.nativeElement.innerHTML = 'Loading User ID ...'; this.peopleSvc.check(this.selectedPerson['name']).then(((u)=>{ this.selectedPersonId = u['id']; this.changeSelectedPerson.emit(this.selectedPersonId); this.element.nativeElement.innerHTML = 'User ID: ' + this.selectedPersonId; }).bind(this)); } constructor(element: ElementRef, renderer: Renderer,peopleSvc:PeopleSvc) { this.peopleSvc = peopleSvc; //this.element指向当前指令的元素引用,我们可动态的修改指令元素的属性,已达到对输入属性的分析结果展示 this.element = element; } }
<!--people-finder.component.html-->
<!--以标签形式使用people-resolver,selectedPerson做为输入属性的值,当changeSelectedPerson发送一个事件时,调用onSelectedUserIdChange方法,并通过$event获取事件携带的参数的引用--> <people-resolver [selectedPerson]="selectedPerson" (changeSelectedPerson)="onSelectedUserIdChange($event)"> </people-resolver>
//people-finder.component.ts
import {
Component
} from '@angular/core';
import { PeopleSvc } from './people';
import { User } from '../../../models/business/User';
import { Utilities } from '../../../utils/appUtilities';
@Component({
selector: 'people-finder',
templateUrl: './people-finder.component.html',
styleUrls: ['./people-finder.component.css'],
providers:[
PeopleSvc
]
})
export class PeopleFinderComponent implements{
selectedUserId:string = '';
selectedPerson:User = null;
constructor(private peopleSvc:PeopleSvc){
}
onSelectedUserIdChange($event){
//定义onSelectedUserIdChange方法
this.selectedUserId = $event;
}
}
这样我们就可以实现people-fnder组件和people-resolver指令之间的参数异步的传递和接收,在使用指令people-resolver时,我们需要在app.module.ts 的declarations中引入PeopleResolver.
3. 通过route的data配置和Route Resolver来异步为一个路由准备数据,通过ActivitedRoute来获取当前route的data来获取。