[英]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.