[英]Dynamic Ionic2 service methods
我正在嘗試使用動態創建的方法編寫服務。
test.service.ts:
import {Injectable} from '@angular/core';
@Injectable()
export class TestService {
constructor() {
}
init(defaults: any) {
Object.keys(defaults).forEach(key => {
this[key] = (val?: any) => {
console.log(key, val)
}
});
}
}
app.component.ts
export class MyApp {
constructor(public platform: Platform,
private test:TestService) {
this.initializeApp();
test.init({
foo: 'bar'
});
console.log(test);
test.foo('foobar');
}
initializeApp() {
this.platform.ready().then(() => {
StatusBar.styleDefault();
Splashscreen.hide();
});
}
}
因此,當我注釋掉test.foo('foobar');
這是對的。 當我取消注釋該行時,它可以正常工作(可以在控制台中看到),但出現Typescript錯誤:
[21:42:12] typescript: src/app/app.component.ts, line: 28 Property 'foo' does not exist on type 'TestService'. L27: console.log(test); L28: test.foo('foobar');
我無法理解,因為在轉換服務時沒有該方法。 我的問題是我如何告訴Typescript我不在乎。
我可以使用test['foo']('foobar')
但我不想...
init<Defaults>(defaults: Defaults): this & Defaults {
return Object.assign({}, this, defaults);
}
應該可以解決問題,但是由於我們要返回一個新值而不是對其進行修改,因此,我們應該將方法從init
重命名為withDefaults
東西,例如構建器模式,並像這樣使用它。
const withDefaults = test.withDefaults({
foo: 'bar'
});
console.log(withDefaults.foo);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.