与多个组件共享服务

时间:2016-08-09 09:30:48

标签: angular angular2-services

我想在我的应用程序上分享一些服务,这些服务负责我的节点服务器上的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           在eval(app / components / team / index / team.index.component.js:48:77)

我的app和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显然有点奇怪。如果我添加此导入它运行良好,但根据文档,我将使用不同的服务实例。

2 个答案:

答案 0 :(得分:1)

也许这是一个错字,但您忘记在TeamApiService组件的模块中导入TeamIndexComponent类:

import { TeamApiService } from '...';

答案 1 :(得分:0)

在要使用服务的组件中导入服务时没有任何问题。

文档说,

当您将服务包含在组件的providers:[]中时,系统会创建一个新的服务实例。

如果你使用你的服务,那就没关系了:

main.ts

中导入您的服务
import {TeamApiService} from "./services/api/team.api.service";
bootstrap(TeamIndexComponent,[TeamApiService ]
).then(
    success => console.log('App bootstrapped!'),
    error => console.log(error)
);

然后,您的整个应用只能访问一个服务实例。

然后你可以在你想要的任何组件中使用这个实例。

组件1

import {TeamApiService} from "./services/api/team.api.service";
import {Component} from '@angular/core'
@Component({
selector:'demo',
templateUrl:'demo.component.html',    
})
export class DemoComponent{
    //inject the service in your current component
    constructor(private _teamApiService:TeamApiService){

    }
}

确保您没有在provider:[]数组中指定您的服务,因为它将创建新实例。

希望这有帮助。