Angular2。扩展输入装饰器

时间:2017-01-29 13:46:31

标签: angular

我经常需要在组件中使用输入值流。通常我这样做:

export class UserComponent {
    userId$ = new BehaviorSubject<number>(null);
    @Input() set userId(value: number) {
       this.userId$.next(value);
    }
}

我想知道有没有办法创建Input$装饰器:

export class UserComponent {
    @Input$() userId$ = new BehaviorSubject<number>(null);
}

1 个答案:

答案 0 :(得分:3)

是的,有可能,您可以创建额外的装饰器,它将使用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);
            }
        });
    }
}