2016-04-27 55 views
0

沒有提供錯誤我想寫類,將範圍的HTTP和添加頁眉到每個請求,但是當我嘗試注入這個類供應商,我得到這個錯誤:在角2

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 
     }); 
    } 
} 

感謝您的幫助。

回答

0

我看到你的服務的錯誤:

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

而且你需要有供應商「看得見」,從部件,其中該DealProvider類被注入。它可以是在部件本身或上部在噴射器樹:

  • 在組件

    bootstrap(AppComponent, [ DealProvider ]); 
    

注:boostrapping主要成分時

@Component({ 
    (...) 
    providers: [ DealProvider ] 
}) 
export class SomeComponent { 
    (...) 
} 
  • 注射器只與部件而不是服務連接。

    詳情請參閱此問題:

  • +0

    看起來像'[[Http,Headers]]'實際上應該是'[[Http],[Headers]]'我沒有辦法驗證它。 –

    1

    您需要提供HTTP_PROVIDERS地方:

    bootstrap(AppComponent, [HTTP_PROVIDERS]) 
    
    0

    供應商只需要使用HTTP默認包含,並以使用HTTP的應用程序,你需要將HTTP模塊添加到您的app.module.ts:進口 添加

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

    ,並添加HttpModuleHttpClientModule給進口商