KaustubhN
KaustubhN

Reputation: 295

Inheritance vs Injection in use of Angular 4 service

I am a bit new to world of Angular. I am currently using Angular-4.4.6. My scenario is as follows: I have 3 components (for e.g. C1, C2, C3) each of which use their own services(e.g. S1, S2, S3 resp.) which then call "http.get()" to get the data from rest backend. What I want to know is instead of injecting the "http:HttpClient" in each of the three services, should I just create a 'RestService' class which has all the rest calls like get(), post(), put(), delete() and then:

OR

Are there any performance hits with these two approaches?

Upvotes: 0

Views: 264

Answers (1)

Eliseo
Eliseo

Reputation: 57939

I like to have a "base service"

export class ServiceModel<T>{
    type: string;
    url: string;
    ...
    constructor(private _http: HttpClient) {
    }
    list(): Observable<T[]> {
        return this._http.get<T[]>(this.url)
    }
    ...
}

Then in data1Service

export interface IData1
{
    id:number;
    desc:string;
    ...
}

@Injectable()
export class Data1Service extends ServiceModel<IData1> {
    type:string="data1";
    url:string="myurl/data1";

    constructor(http: HttpClient) {
        super(http)
    }
}

But I don't kwon if this answer resolve your question :(

Upvotes: 1

Related Questions