首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular 2依赖注入

Angular 2依赖注入
EN

Stack Overflow用户
提问于 2017-03-07 15:55:05
回答 1查看 186关注 0票数 1

我将为我的数据服务创建一个基类。我把像post,get,异常处理这样的常用函数放在基类中。派生类只需要继承基类,而不需要Http或仅在基类中使用的必要内容,基类需要自己“解析”它的依赖关系。

代码语言:javascript
复制
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);
    }
}
代码语言:javascript
复制
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);
    }
}

但是我收到了一个异常,比如"No provider for Http",你能告诉我会错过哪一个吗?

如果我在构造器中注入服务,一切都可以正常工作。

EN

回答 1

Stack Overflow用户

发布于 2017-03-07 15:57:15

如果子类没有显式的构造函数,则使用超类的构造函数:

代码语言:javascript
复制
export class DataServiceBase{
  constructor(private http:Http){}
代码语言:javascript
复制
export class ValidationSampleService extends DataServiceBase{
    // constructor(){
    //    super();
    // }

另请参阅

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42643006

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档