我遇到了一个问题,EventEmitter没有将值输出到父组件。这就是我是如何设置的。
main.component.ts (简写版)
...
@Component({
selector: 'my-app',
templateUrl: '/app/views/main.ejs',
directives: [ROUTER_DIRECTIVES],
providers:[AuthService],
inputs:['userLoggedIn']
})
@RouteConfig([
{path:'/logout', name: 'Logout', component: AuthComponent},
])
export class AppComponent implements OnInit, CanReuse{
constructor(private _auth_service: AuthService){
this._auth_service.authChanged.subscribe(data=>this.authChangedHandler(data));
}
public authChangedHandler($event){
alert($event);
}
}
...auth.component.ts (简写版)
export class AuthComponent implements OnInit, CanReuse{
public loggedIn = false;
public user = {};
@Output()
authChanged: EventEmitter<string>;
public selectedTab = "/login";
constructor(private _router: Router, private _location:Location,private _http: Http, private _auth_service: AuthService){
this.authChanged = new EventEmitter();
this.authChanged.emit("authChanged");
}
}main.ejs (简写版)
<nav (authChanged)="authChangedHandler($event)"></nav>
<router-outlet></router-outlet>auth.service.ts
export class AuthService {
public authChanged: EventEmitter<string>;
constructor(private _http: Http){
this.authChanged = new EventEmitter();
this.authChanged.emit("authChanged");
}
}编辑:,我添加了AuthService代码,并将其注入主组件中。它现在应该起作用,但不起作用。
发布于 2016-02-12 13:41:17
EventEmitter发出的事件不会冒泡。如果将元素添加到router-outlet中,则只有router-outlet接收事件,而不接收包含router-outlet的元素。
可以使用共享服务在父元素和子元素之间进行通信。
有关共享服务,请参见
如果在父组件的providers: []列表中注册共享服务,则该服务仅在父元素及其所有子元素之间共享。如果只将它添加到bootstrap(MyApp, [ ..., SharedService])中,则整个应用程序共享一个实例。
发布于 2016-02-12 13:49:54
实际上,nav不是AuthComponent组件的父组件。后者涉及路由(请参阅router-outlet)。这就是为什么您无法在HTML中的nav元素上接收注册表达式的事件。
https://stackoverflow.com/questions/35363946
复制相似问题