Angular - 在构造函数

时间:2016-09-30 11:37:39

标签: angular typescript angular-services

我试图学习Angular2并且无法设法实现基本服务。一旦我尝试在构造函数中设置brandsService,我就会收到Error: Can't resolve all parameters for SelectListComponent:的错误消息。像这样......

constructor(public brandsService:BrandsService){}

这是我的代码......

组件

import {Component, OnInit} from '@angular/core';
import {BrandsService} from '../services/brands.service';


@Component({
    selector: 'select-list',
    template: `<h1>hello world</h1>`,
    styleUrls: [
        './css/app/form-elements.css'
    ],
    providers: [
        BrandsService
    ]
})

export class SelectListComponent implements OnInit {

    constructor(public brandsService:BrandsService){}

    ngOnInit(): void {}
}

服务

import { Injectable } from '@angular/core';

@Injectable()
export class BrandsService {
    brands = [
        {id: 1, name: "Brand One"}
    ];
}

这是我的 app.module.ts 代码

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';    

import { AppComponent } from './app.component';    
import {BrandsService} from "./services/brands.service";
import {SelectListComponent} from './filter-list/filter-list.component';

@NgModule({
    imports:      [ BrowserModule ],
    declarations: [
        AppComponent,
        SelectListComponent
    ],
    bootstrap: [
        AppComponent
    ],
    providers: [
        BrandsService
    ]
})

export class AppModule { }

2 个答案:

答案 0 :(得分:0)

确保您在main.ts文件中Query Results内的providers中包含服务。您可以像这样导入它:

@NgModule

或者像这样从services文件夹中的index.ts文件导入所有服务,并确保将import services from './app/common/services/BrandsService'; @NgModule({ bootstrap: [AppComponent], declarations: [...], providers: [BrandsService, ...], imports: [...] }) export class AppModule{} 导入到该index.ts文件中:

main.ts

BrandsService

/services/index.ts

import services from './app/common/services';

@NgModule({
  bootstrap: [AppComponent],
  declarations: [...],
  providers: [services, ...],
  imports: [...]
})
export class AppModule{}

答案 1 :(得分:0)

您无法在providers元数据中使用@Component。您必须设置providers并在模块中声明所有组件,如下所示:

@NgModule({
  imports     : [HttpModule],
  declarations : [SelectListComponent],
  providers : [BrandsService]
})
export class AppModule {
}

从组件元数据中删除providers: [BrandsService]