[英]Angular2. Extending Input decorator
我经常需要在组件中使用输入值流。 通常我这样做:
export class UserComponent {
userId$ = new BehaviorSubject<number>(null);
@Input() set userId(value: number) {
this.userId$.next(value);
}
}
我想知道有没有办法创建Input$
decorator:
export class UserComponent {
@Input$() userId$ = new BehaviorSubject<number>(null);
}
是的,有可能,你可以创建额外的装饰器,它将用getter / setter对替换class field,getter将返回Subject
,setter将在这个主题上做next
。
请注意,它可能会破坏AOT编译。
@Input()
@Reactive(false)
public subject:Subject<boolean>; //you don't even need to initialize
export function Reactive(initialValue:any):Function
{
return function(target:Object, property:string)
{
const name:string = `__subject_${property}`;
Object.defineProperty(target, name, <PropertyDescriptor>{
enumerable : false,
configurable: false,
writable : true
});
Object.defineProperty(target, property, <PropertyDescriptor>{
enumerable : true,
configurable: false,
get : function():any
{
if(this[name] === undefined)
{
this[name] = new BehaviorSubject<any>(initialValue);
}
return this[name];
},
set : function(val:any):void
{
if(this[name] === undefined)
{
this[name] = new BehaviorSubject<any>(initialValue);
}
this[name].next(val);
}
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.