components – Angular 2如何将变量从父组件传递到路由器出口
发布时间:2020-12-17 07:21:20 所属栏目:安全 来源:网络整理
导读:我找到的所有教程和答案都只显示了如何使用输入将变量从父组件传递给子组件,但是这个子组件包含在路由器出口中而不是直接在父模板中? 例如: 主要部分 @Component({ selector: 'my-app',template: ` Main page router-outlet/router-outlet `,directives: [
我找到的所有教程和答案都只显示了如何使用输入将变量从父组件传递给子组件,但是这个子组件包含在路由器出口中而不是直接在父模板中?
例如: 主要部分 @Component({ selector: 'my-app',template: ` Main page <router-outlet></router-outlet> `,directives: [ROUTER_DIRECTIVES] }) @RouteConfig([ { path: '/contact',name: 'Contact',component: ContactComponent},]) export class AppComponent{ public num:Number = 123; } @Component({ selector: 'contact-page',template: 'contact page' }) export class ContactComponent{ public num:Number; } 因此,在此示例中,主组件模板包含一个路由器插座,其中将呈现子接触组件,但如何在父组件组件的路由器插座内评估的子组件中获取变量“num”值?
我只是偶然发现了这个问题,这就是我如何解决类似的问题.
我会用一个服务来解决这个问题.然后,所有子项和父项都可以设置该属性,并为所有订阅者传播更改.首先,我将创建一个具有私有BehaviorSubject的服务,该服务具有公共getter和setter,以封装ReplaySubject并仅返回Observable: private _property$: BehaviorSubject<number> = new BehaviorSubject(1); set property(value: number) { this._property$.next(value); } get property$(): Observable<number> { return this._property$.asObservable(); } 使用新的BehaviorSubject(1)的原因是将初始值设置为1,因此可以订阅. 在父onInit中,我会选择property(num)的默认值: private _propertySubscribtion: Subscription ngOnInit() { // set default value to 5 this._componentService.property = 5; // If property is updated outside parent this._componentService.property$.subscribe(p => { this.property = p; }); } ngOnDestroy() { this._propertySubscribtion.unsubscribe(); } 在一个或多个子组件中,可以订阅更改: private _propertySubscribtion: Subscription ngOnInit() { this._propertySubscribtion = this._componentService.property$.subscribe(p => { this.property = p; }); } ngOnDestroy() { this._propertySubscribtion.unsubscribe(); } 如果某个孩子或父母更新了该财产: updateProperty() { // update property this._componentService.property = 8; } 所有订阅者都会知道它. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |