2017-02-09 39 views
0

我想學習Angular2,但有點麻煩。我有一個名爲ParentService服務和提供商的遺傳和多態性

export abstract class ParentService { 

} 

抽象服務類和擴展ParentService另一個服務類稱爲​​

export class ChildService extends ParentService { 

} 

然後,我有叫input.component

import { Component } from "@angular/core"; 

import { ParentService } from "./service/parent.service"; 

@Component({ 
    selector: 'app-input', 
    templateUrl: './input.component.html' 
}) 
export class InputComponent { 
    constructor(private parentService: ParentService) {} 

} 

和組件類在我app.component我提供了一個ChildService實例

import { Component } from '@angular/core'; 
import { ChildService } from './service/child.service'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'], 
    providers: [ChildService] 
}) 
export class AppComponent { 

} 

但是,這不起作用。它建立正常,但在運行應用程序時,我得到一個錯誤 :

EXCEPTION: Error in ./AppComponent class AppComponent - inline template:4:16 caused by: No provider for ParentService! 

這是可能的嗎?我只想要input.component知道ParentService。我真的不希望它知道實施。

+0

你應該避免這種模式 –

+0

@AluanHaddad你可以詳細說明爲什麼它會是壞的? – eric

+0

在任何語言,尤其是JavaScript中,繼承都應該保持在最低水平。由於JavaScript缺乏接口,而TypeScript接口是結構化的,我看到很多人試圖將類用作接口。這是一個可怕的做法。你應該編程接口,而不是實現。即使在缺乏清晰界面的語言中也是如此。 –

回答

2

您不能指望Angular2自動將子類連接到原始類聲明。如果你有兩個子類DogServiceCatService,它們都繼承AnimalServiceproviders列表中聲明,應該使用哪一個?

相反,你需要明確指定:

providers: [{provide: ParentService, useClass: ChildService}] 

文檔:https://angular.io/docs/ts/latest/guide/dependency-injection.html

2

這是可能的,但有一點補充。

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'], 
    providers: [{provide: ParentService, useClass: ChildService}] 
}) 
export class AppComponent { 

} 

這裏的疑問是角度2中的DI不會試圖推斷類之間的任何關係。所以,默認情況下爲了注入ParentService你需要必須提供ParentService,期限。幸運的是,我們可以用上面的構造覆蓋這種行爲。它從字面上告訴DI容器「如果有人要求ParentService,然後創建並給它們一個ChildService實例」。

+0

這給了我錯誤「沒有爲ChildService提供者!」現在。我必須從我的app.module提供一個ChildService實例到我的app.component嗎?我試過了,現在它可以工作。所以我猜AppComonent不會創建ChildService的實例。 – eric

+0

抱歉,忽略該評論。我仍然有幾個組件中的ChildService。這就是我得到錯誤的原因。現在都好。謝謝! – eric