繁体   English   中英

未在Angular2中注入服务

[英]Service not injected in Angular2

我正在尝试将以下服务注入组件:

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

@Injectable()
export class ColorService {       
  private colorPalettes = [

        [
            'rgba(36, 123, 160, 1)',
            'rgba(112, 193, 179, 1)',
            'rgba(178, 219, 191, 1)',
            'rgba(243, 255, 189, 1)',
            'rgba(255, 22, 84, 1)'
        ]
  ]
  constructor() { // some calculations
  }
}

然后按如下方式注入:

import { Component , Input } from '@angular/core';
import { ColorService } from '../colors.service';

@Component({
  moduleId: module.id,
  selector: 'search-form',
  templateUrl: 'search-form.component.html',
  styleUrls: [ 'search-form.component.css']
})

export class SearchFormComponent {
    @Input() colors : ColorService;

    onTagsAdded(tag) {
        console.log(this.colors);
    }
}

但是this.colors是未定义的。 我也将ColorService设置为app.module中的提供者,以便注入它。

要在组件中使用服务,您必须按照以下步骤进行:

import { Component } from '@angular/core';
import { ColorService } from '../colors.service';

@Component({
  moduleId: module.id,
  selector: 'search-form',
  templateUrl: 'search-form.component.html',
  styleUrls: [ 'search-form.component.css']
})

export class SearchFormComponent {

    constructor(private colors: ColorService ) {
        console.log(this.colors);
    }
}

要添加到@ ranakrunal9的答案中,请确保在使用它的模块(例如,您的应用程序模块)中将其标记为提供程序:

import { NgModule }      from '@angular/core';
import { HttpModule } from '@angular/http';
import { BrowserModule } from '@angular/platform-browser';
import './rxjs-operators';

import { AppComponent }  from './app.component';
import { NavModule } from './shared/nav/nav.module';
import { ThisService } from './shared/this.service';
import { ThatService } from './shared/that.service';

@NgModule({
  imports:      [ BrowserModule, HttpModule, NavModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ],
  providers:    [ ThisService, ThatService ] // this is the important part
})

export class AppModule { }

您的search-form元素应具有定义@Input()的属性colors (由于@Input() )。

<search-form [color]="myColorService" />

并且在与视图关联的组件中,您还应该注入ColorService并在构造函数中定义myColorService

constructor(private myColorService: ColorService) {
}

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM