-
Notifications
You must be signed in to change notification settings - Fork 1
Service Implementation
The components in the app scaffold depend on a number of services to deliver concrete data based on the context. The package ship with a number of mock services, but in an implementation you will want to provide your own service implementation with meaning full data in the context.
The app scaffold module relies on dependency injection in order to inject concrete service implementations into components. That way, the components are not tightly bound to a particular implementation, but rather to the contract.
There are three steps necessarily to inject your own services:
- Understand the contract of the service for which you are creating a concrete implementation
- Subclass the mock service class for the service in question and implement the contract by overloading the appropriate methods.
- Register your service as a provider in the NgModule definition of your app.
For step 1, please see the appropriate documentation for the service in this wiki. Steps 2 and 3 are illustrated below.
Generally, you will want to build your own service realizations. For example, consider the Hero Service. To create your own service realization, simply implement an injectable class extending the HeroService included in the package (in this example, we are implementing the GetData() and Logout() methods of the service contract and rely of the default implementation in the base class for the remainder of the contract:
import { Component, Injectable } from '@angular/core';
import { Hero, HeroService } from 'ng2-app-scaffold';
@Injectable()
export class MyHeroService extends HeroService{
constructor(){
super();
this._supportsLogout = true;
this._postLogoutRedirectUrl = "/login";
}
protected GetData(){
if (this._hero) return;
//
// add payload to get user info from backend system.
//
this._hero = new Hero(...);
// get data is called by the promise resolver, which will return the
// Hero object as part of the promise resolution.
}
public Logout():Promise<string>{
return new Promise<string>((resolve, reject) => {
let success: boolean = true;
//
// implement payloadto facilitate logout
//
if (success) {
resolve("You have been successfully logged out..");
}
else {
reject("There was an error...");
}
});
}
}
Note: the caller of Logout is expected to first check the
SupportsLogoutproperty and then perform a redirection toPostLogoutRedirectonce the logout promise is resolved.
Once you have created your service implementation, you can inject it during NgModule registration:
@NgModule({
bootstrap: [ ... ],
declarations: [...],
imports: [...],
providers: [
{
provide: HeroService, deps: [], useFactory: HeroProviderFactory }
}
]
})
export function HeroProviderFactory(...){
return new MyHeroService();
}
Note: The provider factory was moved into an exported method to accomodate Angular 4 requirements to no have lambda functions in the provider loading.