Typescript generic service

后端 未结 3 414
礼貌的吻别
礼貌的吻别 2021-01-30 14:16

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.

3条回答
  •  猫巷女王i
    2021-01-30 14:48

    You can create an abstract generic class and two children class that inherits from it :

    abstract class:

    export abstract class AbstractRestService {
      constructor(protected _http: Http, protected actionUrl:string){
      }
    
      getAll():Observable {
        return this._http.get(this.actionUrl).map(resp=>resp.json() as T[]);
      }
      getOne(id:number):Observable {
        return this._http.get(`${this.actionUrl}${id}`).map(resp=>resp.json() as T);
      }
    } 
    

    driver service class

    @Injectable()
    export class DriverService extends AbstractRestService {
      constructor(http:Http,configuration:Configuration){
        super(http,configuration.serverWithApiUrl+"Driver/");
      }
    }
    

    car service class

    @Injectable()
    export class CarService extends AbstractRestService {
      constructor(http:Http,configuration:Configuration) {
        super(http,configuration.serverWithApiUrl+"Car/");
      }
    }
    

    Note that only the concrete classes are marked as @Injectable() and should be declared inside a module while the abstract one should not.

    update for Angular 4+

    Http class being deprecated in favor of HttpClient, you can change the abstract class to something like that:

    export abstract class AbstractRestService {
      constructor(protected _http: HttpClient, protected actionUrl:string){
      }
    
      getAll():Observable {
        return this._http.get(this.actionUrl) as Observable;
      }
    
      getOne(id:number):Observable {
        return this._http.get(`${this.actionUrl}${id}`) as Observable;
      }
    } 
    

提交回复
热议问题