我有一些使用组件传递变量的应用程序。在那里,我们决定引入嵌套路由。问题在于,子组件需要先订阅,然后才能在此处导航。
export const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeLayoutComponent, canActivate: [AuthGuard],
runGuardsAndResolvers: 'always', children: [
{ path: 'mainDataPanel', component: MainDataPaneComponent, outlet: 'mainPanel'}
] },
{ path: AppUrls.LoginComponentPath, component: LoginComponent }
];
我的html外观:
<mat-sidenav-container class="sidenav-container">
<mat-sidenav
#drawer
class="sidenav"
(...)
<app-tree></app-tree>
</mat-sidenav>
<mat-sidenav-content>
<mat-toolbar color="primary">
<button (...)
aria-label="Toggle sidenav"
(click)="drawer.toggle()"
>
</button>
(...)
<button mat-button ><a [routerLink]="[{ outlets: { mainPanel: ['timeseries'] } }]">Simulation</a></button>
</mat-toolbar>
<router-outlet name="mainPanel"></router-outlet>
</mat-sidenav-content>
</mat-sidenav-container>
用户必须从sidenav中选择任何节点,我应该通知其他组件。
通信组件:
@Injectable({
providedIn: 'root'
})
export class ComponentInteractionsService {
// Observable scenario sources
private selectedNode = new Subject<TreeNode>();
// Observable scenario streams
selectedNode$ = this.selectedNodeSource.asObservable();
// Service message commands
selectedNode(node: TreeNode) {
this.selectedNodeSource.next(node);
}
}
最后:
我的树在单击节点后运行:
this.componentInteractionsService.selectedNode(node);
与尚未激活的组件有关的问题,因此我不会订阅“ stream”:
export class MainDataPaneComponent implements OnInit {
private nodeGuid: string;
constructor(private componentInteractionsService: ComponentInteractionsService) {
(...)
componentInteractionsService.selectedNode$.subscribe(n => this.nodeGuid = n.NodeGuid);
console.log('test2');
}
ngOnInit() {
componentInteractionsService.selectedScenario$.subscribe(n => this.nodeGuid = n.NodeGuid);
console.log('test');
}}
当前,我需要导航到MainDataPaneComponent组件才能激活它,然后一切正常(单击树触发器动作)。
如何在未激活或导航到的组件中订阅流?无需显式导航到组件就可以运行组件的构造函数吗?
谢谢您的回答