2016-05-23 77 views
1

我有一個根組件,它是AppComponent,我已經在根組件(ProductService)中注入了一個服務,我試圖在其中一個子組件(ProductList)中解析該服務。我在發生錯誤角2中的等級依賴注入

沒有爲ProductService提供服務! (ProductListComponent - > ProductService)

這裏是根組件和兒童組件的代碼

import { 
 
    Component 
 
} 
 
from 'angular2/core' 
 
import { 
 
    ProductListComponent 
 
} 
 
from './products/product-list.component' 
 
import { 
 
    ProductService 
 
} 
 
from './products/product.service' 
 

 
/** 
 
* AppComponent 
 
*/ 
 

 
@ 
 
Component({ 
 
    selector: 'pm-app', 
 
    template: ` 
 
    <div> 
 
     <h1>{{PageTitle}}</h1> 
 
     <pm-products></pm-products> 
 
    </div> 
 
    `, 
 
    providers: [ProductService], 
 
    directives: [ProductListComponent] 
 

 
}) 
 
export class AppComponent { 
 
    PageTitle: string = "Acme Product Management"; 
 
}

ProductListComponent

@Component({ 
 
    selector: 'pm-products', 
 
    templateUrl: 'app/products/product-list.component.html', 
 
    styleUrls: ['app/Products/products-list.component.css'], 
 
    pipes: [ProductFilterPipe], 
 
    directives: [StarComponent] 
 
}) 
 
export class ProductListComponent implements OnInit { 
 
    PageTitle: string = "Product List"; 
 
    imageWidth: number = 50; 
 
    imagemargin: number = 2; 
 
    showImage: boolean = false; 
 
    filterBy: string; 
 
    products: IProduct[]; 
 
    
 
    constructor(public _productService:ProductService){ 
 
     
 
    } 
 
    }

我對角度2 DI的理解是,如果服務是以root身份注入的,它會注入到它的子組件中。我需要做額外的事嗎?

+0

恕我直言,所有看起來不錯。你可以在'ProductListComponent'的構造函數中'new ProductService()'而不是注入它嗎?只是爲了檢查這是否會產生更有用的錯誤消息。 –

+0

@GünterZöchbauer我試過了,我可以使用它。另外我已經將Provider參數添加到產品列表組件,甚至工作正常。只有孩子的根組件存在問題。 – satish

+0

我不知道您的意思是「將Provider參數添加到產品列表」。 –

回答

0

您在ProductListComponent中有import { ProductService } from './products/product.service',對吧?