Search code examples
angularcoding-styleangular-services

Is good practice to create one generic service?


I am new in Angular 2. I wonder what is good practice. I created a service where I had a method. Then, I saw that I can use generic service and propably I can use it in more cases. Below I present code from it.

getSpecific(): Promise<ResponseApi<MyModel>> {
    return this._http.get('api/specific')
        .map((response: Response) => <ResponseApi<MyModel>>response.json())
        .toPromise()
        .catch((error) => { throw (error) });
}

getGeneric<T>(url: string): Promise<T> {
    return this._http.get(url)
        .map((response: Response) => <T>response.json())
        .toPromise()
        .catch((error) => { throw (error) });
}

What is good practise? Use different services or use one generic service like in this case. ReponseApi is my model where I have properties like StatusCode and Result.


Solution

  • Well if you want to talk about good practice, you should

    • Stop using promises, as Observables are way better
    • Use the new HttpClient, as the old Http is being deprecated
    • Handle your error instead of throwing it

    Other than that, services are made to be reusable. I don't see why you should not have a common service. You can also make services that use this service.

    For instance, this is usually what I do with firebase : one generic service that is being called by several specific services.