I\'m new to typescript and angular2/4 and I\'m building a single app that have two basic entities which is Car and Driver and all I do is to list them with an API call.
Have a base service for your app.
With get
post
and delete
methods with your base URL
attached.
export class HttpServiceBase {
HOST_AND_ENDPOINT_START : string = 'you/rD/efa/ult/Url' ;
public getWebServiceDataWithPartialEndpoint(remainingEndpoint: string): Observable {
if (!remainingEndpoint) {
console.error('HttpServiceBase::getWebServiceDataWithPartialEndpoint - The supplied remainingEndpoint was invalid');
console.dir(remainingEndpoint);
}
console.log('GET from : ' , this.HOST_AND_ENDPOINT_START + remainingEndpoint);
return this.http.get(
this.HOST_AND_ENDPOINT_START + remainingEndpoint
);
}
This a useful implementation as it allows you to easily debug WS calls - all calls end up coming from the base.
HOST_AND_ENDPOINT_START
can be overriden by any module that you want to extend the base service.
Lets pretend your endpoint is something like:
/myapp/rest/
And you want to implement a HttpSearchBase
you can simply extend HttpServiceBase
and override HOST_AND_ENDPOINT_START
with something like:
/myapp/rest/search
Example CarDriverService
@Injectable()
export class CarDriverService extends HttpServiceBase{
//here we are requesting a different API
HOST_AND_ENDPOINT_START : string = '/myapp/rest/vehicle/;
getAllCars() : Observable{
return this.getWebServiceDataWithPartialEndpoint('/Car')
.map(res => res.json())
}
getAllDrivers(){
return this.getWebServiceDataWithPartialEndpoint('/Driver')
}
addNewDriver(driver: Driver){
return this.postWebServiceDataWithPartialEndpoint('/Driver/',driver)
}
}