简体   繁体   中英

Angular 2 Dependencies Injection

I am going to have a base class for my data services. I place common function like post, get, exception handler in the base class. Derived class just need to inherit the base class without Http or necessary stuff only used in the base class, the base class need to "resolve" it dependencies by itself.

import { Injectable, ReflectiveInjector } from '@angular/core'
import { Http, RequestOptions, Headers, Request, Response } from '@angular/http';
import { Observable } from 'rxjs';

export class DataServiceBase{
    private _injector: ReflectiveInjector;
    private get injector() : ReflectiveInjector{
        if(this._injector == null)
            this._injector = ReflectiveInjector.resolveAndCreate([Http]);

        return this._injector;
    }

    private _http: Http;
    private get http(): Http{
        if(this._http == null)
            this._http = this.injector.get(Http);

        return this._http;
    }

    private extractData(res: Response) {
        let body = res.json();
        return body || {};
    }

    private handleException(exception: any) {
        console.error(exception);
        return Observable.throw(exception.statusText);
    }

    protected post(url: string, data: any): Observable<any> {
        var headers = new Headers({ 'Content-Type': 'application/json' });
        var options = new RequestOptions({ headers: headers });

        var body = JSON.stringify(data);

        return this.http.post(url, body, options)
            .map(this.extractData)
            .catch(this.handleException);
    }

    protected get(url: string) : Observable<any> {
        return this.http.get(url)
            .map(this.extractData)
            .catch(this.handleException);
    }
}
import { Injectable } from '@angular/core'
import { Observable } from 'rxjs';

import { TodoItem } from '../model/todoItem';

import { DataServiceBase } from './dataServiceBase';

@Injectable()
export class ValidationSampleService extends DataServiceBase{
    constructor(){
        super();
    }

    public getAllTodoItem(): Observable<any>{
        return this.get('/api/todo');
    }

    public updateToDoItem(item: any){
        return this.post('/api/todo/updateTodoItem', item);
    }
}

But I got an exception like "No provider for Http", can you advise which one I might miss?

Everything was working just fine if I inject services in constructor.

在此处输入图片说明

If the subclass doesn't have an explicit constructor, then the constructor of the superclass is used:

export class DataServiceBase{
  constructor(private http:Http){}
export class ValidationSampleService extends DataServiceBase{
    // constructor(){
    //    super();
    // }

See also

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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