lol*_*lio 5 angular2-routing angular
在路由配置的根组件中,我有一个按钮.当我单击此按钮时,我想在激活的子路径中触发一个事件.
我一直在努力解决这个问题,而且唯一看起来很有希望的是使用双向服务(链接到角度文档).但是,我不知道如何让它发挥作用.
这是一个证明:
https://plnkr.co/edit/7zDTTTlABWD2GFo01jaz?p=preview
我已经设置了一个简单的路由配置,它自动重定向到TestComponent.当我点击路线应用程序级别的"单击"按钮时,我希望能够clickDetected()在TestComponent中触发该功能.
希望一切都清楚 - 任何建议表示赞赏!
代码如下;
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)
}
}
Run Code Online (Sandbox Code Playgroud)
test.service
@Injectable()
export class TestService {
private clickedSource = new Subject<string>();
clicked$ = this.clickedSource.asObservable();
declareClick(value: string) {
console.log(value)
return this.clickedSource.next(value);
}
}
Run Code Online (Sandbox Code Playgroud)
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)
})*/
}
}
Run Code Online (Sandbox Code Playgroud)
你只需要.subscribe()对Observable所接收的.next()事件:
this.testService.clickedSource.subscribe((val)=>{
console.log(2, val);
});
Run Code Online (Sandbox Code Playgroud)
固定的Plunker:https://plnkr.co/edit/aPR6KvuOi2tgQXLgokHi ? p = preview
| 归档时间: |
|
| 查看次数: |
1540 次 |
| 最近记录: |