Hi.
I need to change some behaviors according to platform, so I created different platform-based services (with the same parent class).
Now I have to provide the right service. I think to use something like:
var serviceClass = NameService;
if (platform.is('ios') {
serviceClass = IosNameService;
} else if (platform.is('android') {
serviceClass = AndroidNameService;
}
return { provide: NameService, useClass: serviceClass }
But platform is not ready on initialization time.
How can I reach the same result?
Thank you.
If you don’t get any better answers, what I would do is ditch inheritance in favor of composition and delegation. From a DI consumer perspective, there is only NameService
. Inside NameService
there is a delegate object that you create explicitly.
export class NameService {
private _delegate: IosNameService | AndroidNameService;
private _ready: Promise<void>;
constructor(plat: Platform) {
this._ready = plat.ready().then(() => {
if (plat.is('android')) {
this._delegate = new AndroidNameService();
} else if (plat.is('ios')) {
this._delegate = new IosNameService();
}
});
}
ready(): Promise<void> {
return this._ready;
}
frobulate(foo: string): string {
return this._delegate.frobulate(foo);
}
}
Thank you @rapropos .
I adopted a similar solution:
export class PlatformBasedService {
public nameService:NameService;
constructor(plat: Platform) {
this._ready = plat.ready().then(() => {
if (plat.is('android')) {
this.nameService = new AndroidNameService();
} else if (plat.is('ios')) {
this.nameService = new IosNameService();
}
});
}
}
AndroidNameService and IosNameService implement NameService interface.
Pros:
- Who uses nameService knows that is platform based.
- Who implements AndroidNameService and IosNameService have to respect a common interface.
Cons:
- Goodbye Angular service injection