デコレータTopicClass
を作成して、装飾されたコンポーネントにプロパティと関数を追加したいとします。この関数は、注入されたサービスにアクセスする必要があります。 どうすればいいですか?ここで依存関係注入サービスにアクセスする角2のクラス・デコレータ
に失敗した試みたものです:
@Component({
selector: 'home',
styleUrls: ['./home.component.css'],
templateUrl: './home.component.html'
})
@TopicClass('home')
export class HomeComponent {
constructor(private topicService: TopicService) { }
}
は私が挿入された機能ngAfterViewInit
を通じて注入サービスにアクセスすることはできません。
export function TopicClass(title: string) {
return function (target: Function) {
const original = target;
function construct(constructor, args) {
const c: any = function() {
return constructor.apply(this, args);
}
c.prototype = constructor.prototype;
const newInstance = new c();
newInstance['topic'] = new Topic(title, '');
newInstance['ngAfterViewInit'] =() => {
newInstance['topicService'].setTopic(newInstance['topic']);
}
return newInstance;
}
const ctor: any = (...args) => {
console.log("Service: " + original.prototype.topicService);
return construct(original, args);
};
ctor.prototype = original.prototype;
return ctor;
}
}
問題はnewInstance['topicService']
は未定義です。
:私も意図したとおりに動作し、簡単な活字体のプログラムに問題を再現してみました https://github.com/ptea/angular-class-decorator-test
https://github.com/ptea/angular-class-decorator-test/blob/master/src/app/services/topic.service.ts
を:
newInstance['printStreet'] =() => {
console.log(`printFirstnameStreet: ${newInstance['firstname']}, ${newInstance['street']}`);
}
https://github.com/ptea/angular-class-decorator-test/blob/master/dashboard.ts
任意ideこの問題の解決策として?
。あなたのコードは、 'return target'が削除されたときに機能します。 –
これは天才です! – Slick86