我想在我的應用程序中共享幾項服務,這些服務負責我的節點服務器上的API調用。將服務分享給多個組件
通過下面的官方文檔,這就是我想
// app.component.ts
import { Component } from "@angular/core";
import { ROUTER_DIRECTIVES } from '@angular/router';
import "./rxjs-operators";
import {CampaignApiService} from "./services/api/campaign.api.service";
import {PlatformApiService} from "./services/api/platform.api.service";
import {TeamApiService} from "./services/api/team.api.service";
import {UserApiService} from "./services/api/user.api.service";
@Component({
moduleId: module.id,
selector: 'app',
templateUrl: "app.component.html",
providers: [
TeamApiService,
PlatformApiService,
CampaignApiService,
UserApiService,
],
styleUrls: [],
directives: [ROUTER_DIRECTIVES]
})
export class AppComponent { }
在我的部件之一,現在我想訪問我的team.api.service這應該是訪問,因爲由一個提供父母組件,但我面對這個錯誤
ReferenceError: TeamApiService is not defined at eval (app/components/team/index/team.index.component.js:48:77)
我的應用程序和teamIndex之間的唯一組件是路由器,我可能錯過了一些有關的依賴注射。
這是參與其中導致錯誤
// team.index.component.ts
import {
Component, trigger,
state, style,
transition, animate,
OnInit
} from "@angular/core";
import { JSONP_PROVIDERS } from '@angular/http';
import { TeamShowComponent } from "../show/team.show.component";
import { Observable } from 'rxjs/Observable';
// Users
import { Team } from "../../../models/team.model";
import { TeamService } from "../../../services/team.service";
@Component({
moduleId: module.id,
selector: 'TeamIndex',
templateUrl: "team.index.html",
providers: [JSONP_PROVIDERS, TeamService, TeamApiService],
directives: [TeamShowComponent],
animations: [
trigger('teamSelected', [
state('false', style({
transform: 'scale(1)'
})),
state('true', style({
transform: 'scale(1)',
"z-index": 25
})),
transition('false => true', animate('100ms ease-in')),
transition('true => false', animate('100ms ease-out'))
])]
})
export class TeamIndexComponent implements OnInit {
teams: Observable<Team[]>;
distinctSettings: string[];
mode = "Observable";
selectedTeam: Team;
constructor (private teamService: TeamService, private teamApiService: TeamApiService) {}
ngOnInit() {
this.getTeams();
this.teams.subscribe(
teams => {
this.distinctSettings = this.teamService.getDistinctSettings(teams)
}
)
}
getTeams() {
this.teams = this.teamApiService.getTeams();
}
onSelect(team: Team) {
if (team === this.selectedTeam)
this.selectedTeam = null;
else
this.selectedTeam = team;
}
isSelected(team: Team) {
return team === this.selectedTeam;
}
}
渲染的成分,我覺得顯然是有點怪異沒有進口我team.api.service在我使用它的組件。如果我添加這個導入它運行良好,但根據文檔我將使用我的服務的不同實例。
可能缺少引導'@NgModule({提供商:[]})' 需要把它[附RC5開始,由於拉迪姆·克勒(http://stackoverflow.com/a/39290087/452708) – Abhijeet