1
考慮下面的例子中基類:如何正確地設計一個「基地」角/離子類
import { FormBuilder, FormGroup } from '@angular/forms';
import { NavParams, LoadingController, Loading, Events } from 'ionic-angular';
import { IBaseService } from '../../data/interface/ibase-service';
import { MessageUtil } from '../../message/message-util';
export class FormPage<T> {
public form: FormGroup;
public current: T;
public submitAttempt: boolean;
public loading: boolean;
public mode: string;
public id: number;
public loader: Loading;
constructor(public service: IBaseService<T>,
public fb: FormBuilder,
public events: Events,
public messageUtil: MessageUtil,
public navParams: NavParams,
public loadingCtrl: LoadingController) {
let me = this;
me.mode = navParams.get('mode');
me.id = navParams.get('id');
}
}
現在,我想要做的是爲實現類只提供/注入'服務'參數而不需要傳遞所有其他基本參數。 下面是實現類:
import { Component } from '@angular/core';
import { NavParams, IonicPage, LoadingController, Events } from 'ionic-angular';
import { FormBuilder, FormGroup } from '@angular/forms';
import { MessageUtil } from '../../framework/message/message-util';
import { FormPage } from '../../framework/base/page/form-page';
import { UserService } from '../../providers/user-service';
import { User } from '../../models/user';
@IonicPage()
@Component({
selector: 'page-edit-user',
templateUrl: 'edit-User.html',
providers: [
UserService,
MessageUtil
]
})
export class EditUserPage extends FormPage<User> {
//This is the reality
constructor(public service: UserService,
public fb: FormBuilder,
public events: Events,
public messageUtil: MessageUtil,
public navParams: NavParams,
public loadingCtrl: LoadingController) {
super(service, fb, events, messageUtil, navParams, loadingCtrl);
}
//This is my goal
constructor(public service: UserService) {
super(service);
}
}
的目標,如果可能是未通過所有角度和離子成分,因爲他們提供的/在基類級別上聲明已經和各執行類應該只處理w /該服務以避免樣板代碼。
請看看[這個SO答案](https://stackoverflow.com/questions/43029212/typescript-and-multiple-classes/43030491#43030491)。這就是我在我所從事的Ionic Apps中處理它的方式。 – sebaferreras
@sebaferreras我喜歡你所採取的方法,儘管我有點擔心如果這樣會讓班級容易受到副作用的影響。雖然我看到你通過公開的方法暴露了注入的類,但會給人一種印象,他們是類輸入的一部分。有趣。 – Vonzkie
是的,這個想法是爲了避免每個頁面的構造函數中的所有參數,並且還包括一些幫助程序,以避免需要10-15行代碼來顯示警告消息等等。它不包含在答案中,但實際上我定義了兩個基本頁面:'BasePage'和'UserBasePage'。後者有一名警衛在進入之前檢查用戶是否登錄。因此,在'BasePage'中,我還添加了一個'redirectTo' helper,以處理用戶未登錄的場景,所以我捕獲了守衛的返回,如果它是false,它將顯示登錄頁面。 – sebaferreras