ライブラリから来た既存のクラスにいくつかのメソッドを追加したいと思います。Typescriptでは、ライブラリのクラスの拡張メソッドを作成します
はinterface
経由String
、Element
缶延長のようないくつかの基本的なタイプが知られているし、それがprototype
です追加します。
interface String {
extFunc():Function;
}
String.prototype.extFunc = function() {
//blabla
};
"a".extFunc();
また、拡張方法を追加する方法は、Observable<T>
です。
declare module 'rxjs/Observable' {
interface Observable<T> {
foo: String;
}
}
Observable.prototype.foo= "bar";
console.log(Observable.of("a").foo);
しかし、私はからNavController(イオンからLIB)に同じことをしようとするとき、それは私が宣言インターフェイスに全体からNavControllerを上書きします。
declare module 'ionic-angular' {
interface NavController {
replace(page: Page): Promise<any>;
}
}
navCtrl.replace(...); //ok
navCtrl.push(...); //original function => "not exist"
これらのクラスにどのように拡張メソッドを追加するのがよいのでしょうか?感謝〜
編集: あり、実際のコードは
import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {GuidePage} from '../guide/guide.component';
@Component({
selector: 'page-home',
templateUrl: 'home.component.html'
})
export class HomePage {
pageName = "home";
// navCtrl is come from angular2's Dependency Injection,
// it may not suitable to extend NavController
constructor(public navCtrl: NavController) {}
gotoGuide(): void {
//wanna replace this
this.navCtrl.push(GuidePage).then(() => {
let index = this.navCtrl.getActive().index;
this.navCtrl.remove(index - 1);
});
//with this custom extension method
//this.navCtrl.replace(GuidePage);
}
}
ありがとうございましたが、私が追加したいクラスは、angular2のDependency Injectionから来ています。つまり、コンストラクタ()から来ています。詳細はこちらをご覧ください。 https://angular.io/guide/dependency-injection#injectable –
おそらく、依存性注入を含むあなたの実際のコードであなたの質問を明確にすることができます。 – Kokodoko
私は実際のコードを投稿しています、あなたの助言に感謝します。 –