大佬教程收集整理的这篇文章主要介绍了components – Angular 2如何将变量从父组件传递到路由器出口,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
例如:
主要部分
@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; }
所有订阅者都会知道它.
以上是大佬教程为你收集整理的components – Angular 2如何将变量从父组件传递到路由器出口全部内容,希望文章能够帮你解决components – Angular 2如何将变量从父组件传递到路由器出口所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。