我想要做這樣的事情讓我platform=cordova
代碼從我platform=browser
代碼分開angular2如何根據平臺 - cordova或瀏覽器獲取「@ Injectable」的不同子類?
import { Injectable } from '@angular/core';
import { Platform } from 'ionic-angular';
import { File } from 'ionic-native';
declare var window;
@Injectable()
export class ImageSrcService {
constructor(protected platform: Platform){
if (platform.is('cordova')) {
// I want an instance of CordovaService
} else {
// I want an instance of BrowserService
}
}
getSrc(id: string) : Promise<string> {}
}
export class BrowserService extends ImageSrcService {
constructor(protected platform: Platform){
super(platform);
}
getSrc(id: string) : Promise<string> {
const uri = `http://example.com/images/${id}.jpg`;
return Promise.resolve(uri);
}
}
export class CordovaService extends ImageSrcService{
constructor(protected platform: Platform){
super(platform);
}
getSrc(id: string) : Promise<string> {
// File.checkFile('/images/', `${id}.jpg`)
const fullPath = `/images/${id}.jpg`;
return new Promise<string>((resolve, reject)=>{
window.resolveLocalFileSystemURL(
fullPath
, (fileEntry) => {
if (fileEntry.isFile)
return resolve(fileEntry.nativeURL);
reject("File not found");
});
});
}
}
如何使用依賴注入來創建基於所提供的Platform
值,這是在運行時確定正確的實例?
您可以創建兩個服務實例,然後使用依賴注入useFactory功能,您可以決定注入哪個服務。請參閱以下內容以獲取更多信息:https://angular.io/docs/ts/latest/guide/dependency-injection.html – galvan