简体   繁体   English

Angular 4服务中的继承与注入

[英]Inheritance vs Injection in use of Angular 4 service

I am a bit new to world of Angular. 我对Angular有点陌生。 I am currently using Angular-4.4.6. 我目前正在使用Angular-4.4.6。 My scenario is as follows: I have 3 components (for eg C1, C2, C3) each of which use their own services(eg S1, S2, S3 resp.) which then call "http.get()" to get the data from rest backend. 我的情况如下:我有3个组件(例如C1,C2,C3),每个组件都使用自己的服务(例如S1,S2,S3),然后调用“ http.get()”来获取数据从其余后端。 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: 我想知道的是,不是应该在这三个服务中的每一个中注入“ http:HttpClient”,我应该创建一个“ RestService”类,该类具有所有其余的调用,例如get(),post(),put(), delete()然后:

  • extend this base class into each of my 3 services where I will subscribe to these method calls of base class and then use the data fetched? 将此基类扩展到我的3个服务中的每一个中,我将在其中订阅这些基类的方法调用,然后使用获取的数据?

OR 要么

  • inject the 'RestService' which has generic methods into constructor of each of my services and then use these services by subscribing them? 将具有通用方法的“ RestService”注入到我的每个服务的构造函数中,然后通过订阅它们来使用这些服务?

Are there any performance hits with these two approaches? 这两种方法是否会对性能产生影响?

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 然后在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 :( 但是我不知道这个答案是否能解决您的问题:(

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM