我试图在Angular中实现类似委托模式的东西.当用户点击a时nav-item,我想调用一个函数然后发出一个事件,而该事件又由一些其他组件监听事件来处理.
这是场景:我有一个Navigation组件:
import {Component, Output, EventEmitter} from 'angular2/core';
@Component({
// other properties left out for brevity
events : ['navchange'],
template:`
<div class="nav-item" (click)="selectedNavItem(1)"></div>
`
})
export class Navigation {
@Output() navchange: EventEmitter<number> = new EventEmitter();
selectedNavItem(item: number) {
console.log('selected nav item ' + item);
this.navchange.emit(item)
}
}
Run Code Online (Sandbox Code Playgroud)
这是观察组件:
export class ObservingComponent {
// How do I observe the event ?
// <----------Observe/Register Event ?-------->
public selectedNavItem(item: number) {
console.log('item index changed!');
}
}
Run Code Online (Sandbox Code Playgroud)
关键问题是,如何让观察组件观察相关事件?
event-delegation observable observer-pattern eventemitter angular
我希望子组件访问共享服务并在将子组件注入主组件之后获取数据。我想让sharedservice(rootscope)的数据直接把数据放到mainComponents HTML中,就像这里。
主组件.ts
import { Component } from '@angular/core';
import {ChildComponent} from './child';
import {AppServiceService} from './app-service.service';
@Component({
moduleId: module.id,
selector: 'rootscope-app',
templateUrl: 'rootscope.component.html',
styleUrls: ['rootscope.component.css'],
directives:[ChildComponent]
})
export class RootscopeAppComponent {
title = 'rootscope works!';
display:any;
constructor(appServiceService:AppServiceService){
this.display=appServiceService.getter();
}
}
Run Code Online (Sandbox Code Playgroud)
共享服务.ts
import { Injectable} from '@angular/core';
@Injectable()
export class AppServiceService {
ser = "hello i am from service";
public data: any;
constructor() {
}
settter(data: any) {
this.data = data;
}
getter() {
return this.data; …Run Code Online (Sandbox Code Playgroud)