Angular 2中没有提供程序错误

时间:2016-04-27 13:55:44

标签: angular

我正在尝试编写将扩展Http并为每个请求添加标头的类,但是当我尝试将此类注入提供程序时,我收到此错误:

browser_adapter.ts:73 EXCEPTION: Error: Uncaught (in promise): No provider for HttpClient! (ListPage -> DealProvider -> HttpClient)

提供者代码:

import {Injectable} from 'angular2/core';
import {HttpClient} from './http-client';
import 'rxjs/add/operator/map';

/*
 Generated class for the DealProvider provider.

 See https://angular.io/docs/ts/latest/guide/dependency-injection.html
 for more info on providers and Angular 2 DI.
 */
@Injectable()
export class DealProvider {
    static get parameters() {
        return [[HttpClient]]
    }

    constructor(http) {
        this.http = http;
        this.data = null;
    }

    load() {
        if (this.data) {
            return Promise.resolve(this.data);
        }

        return new Promise(resolve => {
            this.http.get('http://apiary-mock.com/deal/list/?page=1&search=ahoj&category=1&city=1')
                .map(res => res.json())
                .subscribe(data => {
                    this.data = data;
                    resolve(this.data);
                });
        });
    }
}

HttpClient类代码

import {Injectable} from 'angular2/core';
import {Http, Headers} from 'angular2/http';

@Injectable()
export class HttpClient {
    static get parameters() {
        return [[Http], [Headers]]
    }

    constructor(http, headers) {
        this.http = http;
    }

    createHeaders(headers) {
        headers.append('AppVersion', '1.0.0');
        headers.append('DeviceIdent', 'uuid');
        headers.append('Session', 'sdawdbkj213345b345hj3b45');
    }

    get(url) {
        let headers = new Headers();
        this.createHeaders(headers);
        return this.http.get(url, {
            headers: headers
        });
    }
}

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

您需要在某处提供HTTP_PROVIDERS

bootstrap(AppComponent, [HTTP_PROVIDERS])

答案 1 :(得分:0)

我在您的服务中看到错误:

@Injectable()
export class HttpClient {
  static get parameters() {
    return [[Http, Headers]]
  }
  (...)
}

此外,您需要提供商"可见"来自注入DealProvider类的组件。它可以位于组件本身或注入器树中的上部:

    组件中的
  • @Component({
      (...)
      providers: [ DealProvider ]
    })
    export class SomeComponent {
      (...)
    }
    
  • 在升级主要组件时
  • bootstrap(AppComponent, [ DealProvider ]);
    

请注意,注入器只链接到组件而不是服务。

有关详细信息,请参阅此问题:

答案 2 :(得分:0)

默认情况下,提供商包含Http,为了在您的应用中使用Http,您需要将HttpModule添加到app.module.ts:导入 添加

import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';

并将HttpModuleHttpClientModule添加到导入程序