【发布时间】:2017-06-13 02:41:16
【问题描述】:
在路由配置的根组件中,我有一个按钮。当我点击这个按钮时,我想在激活的子路由中触发一个事件。
我已经为此苦苦挣扎了一段时间,唯一看起来很有希望的是使用bi-directional service (link to angular docs)。但是,我不确定如何让它工作。
这里有一个 plunk 来演示:
https://plnkr.co/edit/7zDTTTlABWD2GFo01jaz?p=preview
我已经设置了一个简单的路由配置,它会自动重定向到 TestComponent。当我在路由应用级别单击“单击”按钮时,我希望能够触发 TestComponent 中的clickDetected() 函数。
希望一切都清楚 - 任何建议都值得赞赏!
代码如下;
app.component
@Component({
selector: 'my-app',
template: `
<input type="button" (click)="onClick('hello')" value="click" />
<router-outlet></router-outlet>
`,
})
export class AppComponent {
constructor(private testService: TestService) {
}
onClick(v){
this.testService.declareClick(v)
}
}
测试服务
@Injectable()
export class TestService {
private clickedSource = new Subject<string>();
clicked$ = this.clickedSource.asObservable();
declareClick(value: string) {
console.log(value)
return this.clickedSource.next(value);
}
}
test.component
@Component({
selector: 'my-test',
template: `
<div>
<h1>Test Component</h1>
</div>
`,
})
export class TestComponent implements OnInit {
public clicked?: any
constructor(private testService: TestService) {
}
clickDetected(){
console.log("parent clicked")
}
ngOnInit(){
this.testService.declareClick()
/* .subscribe((v) => {
this.clicked? = v;
console.log(v)
})*/
}
}
【问题讨论】: