我正在使用路由功能创建一个带有 Angular 2 的应用程序,并且我有一个由更高层路由之一呈现的弹出组件,我想在呈现的组件中的单击事件上打开它通过其中一条更深的路线。
例如,假设我有一个带有包含弹出窗口的模板的基本路由器:
@Component({
selector: 'application',
template: '<router-outlet></router-outlet><popup-component></popup-component>',
directives: [PopupComponent]
})
@RouteConfig([
{ ... },
{ ... }
])
export class AppRoute { }
还有一个带有 open 方法的简单弹出组件:
@Component({
selector: 'popup-component',
template: '<div [class.show]="isVisible">This is a popup.</div>'
})
export class PopupComponent {
public isVisible: boolean = false;
show() {
this.isVisible = true;
}
}
如何在 AppRoute 已从位于路由树下方某处的另一个组件呈现的特定 PopupComponent 上调用此 show 方法?
我试过像这样使用依赖注入(inject):
@Component({
selector: 'my-component',
template: '<button (click)="showPopup()"></button>'
})
export class MyComponent {
constructor(private popup: PopupComponent) { }
showPopup() {
this.popup.show();
}
}
但这只是创建了一个尚未实际呈现的 PopupComponent 的新实例。如何调用 AppRoute 呈现的那个?
最佳答案
你需要一个共享服务
import {Injectable} from 'angular2/core';
import {Subject} from 'rxjs/Rx';
export class PopupService{
show:Subject<boolean> = new Subject();
}
将服务添加到 AppRoute
中的提供者
@Component({
providers:[PopupService],
selector: 'application',
...
])
export class AppRoute { }
将服务注入(inject)popup-component
并订阅节目主题。
@Component({
selector: 'popup-component',
template: '<div [class.show]="isVisible">This is a popup.</div>'
})
export class PopupComponent {
public isVisible: boolean = false;
constructor(private popup: PopupService) {
popup.show.subscribe( (val:boolean) => this.isVisible = val );
}
}
将它注入(inject)任何你想显示弹出窗口的组件,在show
主题上调用next
;
@Component({
selector: 'my-component',
template: '<button (click)="showPopup()"></button>'
})
export class MyComponent {
constructor(private popup: PopupService) { }
showPopup() {
this.popup.show.next(true);
}
}
关于typescript - Angular 2 : Call existing component from another component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36456564/