【问题标题】:Hierarchical Dependecy Injection in angular 2角度2中的分层依赖注入
【发布时间】:2016-05-23 17:54:34
【问题描述】:

我有一个根组件,它是 AppComponent ,我在根组件 (ProductService) 中注入了一个服务,我试图在其中一个子组件 (ProductList) 中解决它。我在

中遇到错误

没有 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";
}

产品列表组件

@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){
        
    }
  }

我对 Angular 2 DI 的理解是,如果服务被注入到 root 中,它会被注入到它的子组件中。我需要做额外的事情吗?

【问题讨论】:

  • 恕我直言,一切看起来都很好。您可以在ProductListComponent 的构造函数中尝试new ProductService() 而不是注入它吗?只是为了检查这是否会导致更有用的错误消息。
  • @GünterZöchbauer 我试过了,我可以使用它。此外,我已将 Provider 参数添加到产品列表组件中,即使这样也可以正常工作。只有子组件的 Root 组件有问题。
  • 不知道你说的“将Provider参数添加到产品列表”是什么意思。
  • 如果我添加 Provider 参数,那么我将使用产品列表组件。我的意思是当我提供像 @component({provider:[ProductService]}); 这样的代码时在 Productlist 组件中,它能够解决。我期待角度 DI 将 rootcomponent 的提供者注入它的孩子
  • 没错。不知道为什么它在你的情况下不起作用。

标签: javascript angularjs angular


【解决方案1】:

你的ProductListComponent 中有import { ProductService } from './products/product.service',对吧?

【讨论】:

    猜你喜欢
    • 2018-10-16
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多