2016-09-27 83 views
2

我在自定義提供者在Angular 2.0.1中遇到問題。我爲我的http請求創建一個自定義提供程序,爲每個請求添加一個參數,但是當我在用戶服務的提供程序上使用它們時,出現錯誤。@在Angular 2.0.1中注入自定義提供者

HttpClient的(自定義)

@Injectable() 
export class HttpClient { 
    constructor(@Inject(Http) private _http: Http){} 
} 

UserServices

@Injectable() 
export class UsersServices { 
    constructor(@Inject(HttpClient) private _http: HttpClient) {} 
} 

錯誤控制檯:

無法解析UsersServ所有參數冰:(?)。

tsconfig.json(打字稿:2.0.3)

{ 
    "compileOnSave": false, 
    "compilerOptions": { 
    "declaration": false, 
    "emitDecoratorMetadata": true, 
    "experimentalDecorators": true, 
    "target": "es5", 
    "mapRoot": "./", 
    "module": "commonjs", 
    "moduleResolution": "node", 
    "noEmitOnError": true, 
    "noImplicitAny": false, 
    "outDir": "../dist", 
    "sourceMap": true, 
    "typeRoots": [ 
     "../node_modules/@types" 
    ], 
    "types": [ 
     "core-js", 
     "jasmine", 
     "node" 
    ] 
    }, 
    "files": [ 
    "main.ts", 
    "typings.d.ts" 
    ] 
} 

app.module.ts(角度:2.0.1)

@NgModule({ 
    imports: [ 
     CommonModule, 
     RouterModule, 
     HttpModule 
    ], 
    exports: [], 
    declarations: [...], 
    providers: [ HttpClient, UsersServices ], 
}) 
export class AppModule { } 
+0

你不」 t需要使用'@Inj ect(HttpClient)'當'HttpClient'是'@Injectable()' – drewmoore

+0

在角度文檔中: **建議:向每個服務類添加@INJECTABLE()** 我們建議在每個服務類中添加@Injectable()即使是那些沒有依賴關係,因此在技術上也不需要它的人。原因如下: 未來證明:稍後添加依賴關係時,不需要記住@Injectable()。 一致性:所有的服務遵循相同的規則,我們不必奇怪爲什麼一個裝飾器丟失。 –

+0

正確。我指的是構造函數中的@Inject(HttpClient)。當服務是@Injectable()時,你不需要使用'@Inject()',並且我可以看到使用它無論如何都有問題。 – drewmoore

回答

1

的一些小時後在angular的核心調試,我發現了一個解決方案,我不知道它是否正確(最好),但它看起來很有效。

app.module.ts(角:2.0.1)

@NgModule({ 
    imports: [ 
     CommonModule, 
     RouterModule, 
     HttpModule 
    ], 
    exports: [], 
    declarations: [...], 
    providers: [ 
     { provide:"appHttpClient", useClass:HttpClient } 
     , { provide:"appUsersServices", useClass:UsersServices } 
    ] 
}) 
export class AppModule { } 

HttpClient的(自定義)

@Injectable() 
export class HttpClient { 
    constructor(@Inject(Http) private _http: Http){} 
} 

UserServices

@Injectable() 
export class UsersServices { 
    constructor(@Inject("appHttpClient") private _http: HttpClient) {} 
} 
+0

這解決了我的問題。這種方法是否像使用要注入主服務的服務的別名? –

相關問題