更新:我忽略了一个服务,问题实际上是关于注入服务的服务,注入服务的服务。我更新了帖子。
我很难在 Angular 2 应用程序的服务中注入服务,我不确定我是否错误地解释了依赖注入的一些概念。
My situation is as follows:
I have a parentcomponent called app.component that uses a loginservice to authenticate users, this service is bootstraped in the app bootstrapping process.
我还有一个艺术家组件,它使用共享服务,此服务在我的父组件内提供。我想要登录服务也注入我的体内共享服务,这样我就可以在我的共享服务中触发某个操作时注销用户。
不知何故,这总是从我的共享服务返回一个错误,表明我的登录服务未定义。我认为以下行应该可以将我的loginService注入到我的sharedService中:
constructor(@Inject(LoginService) private _loginService: LoginService,
private _router: Router, private _http: Http) { }
_loginService 仍然未定义...有人知道我做错了什么吗?
根据要求相关代码片段:
引导程序.ts
import { APP_BASE_HREF } from '@angular/common';
import { bootstrap } from '@angular/platform-browser-dynamic';
import { ROUTER_PROVIDERS } from '@angular/router';
import { HTTP_PROVIDERS } from '@angular/http';
import { LoginService } from './+login/login.service';
import { AppComponent } from './app.component';
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
HTTP_PROVIDERS,
LoginService
]);
应用程序组件
import { Component, OnInit } from '@angular/core';
....
@Component({
moduleId: module.id,
selector: 'sd-app',
templateUrl: 'app.component.html',
directives: [ROUTER_DIRECTIVES, SidebarMenuComponent, PAGINATION_DIRECTIVES, Growl],
providers: [ArtistService,
SharedService]
})
艺术家组件
import { Component, provide, OnInit } from '@angular/core';
....
@Component({
moduleId: module.id,
directives: [ FORM_DIRECTIVES, Confirm, RequestListComponent,
QuotationListComponent, TOOLTIP_DIRECTIVES, SELECT_DIRECTIVES ],
pipes: [ MapToIterablePipe, DayMonthYearTimePipe ],
templateUrl: 'artist-detail.html'
})
export class ArtistComponent implements OnInit {
constructor(
private _artistService: ArtistService,
public sharedService: SharedService
) { }
艺术家服务
import { Injectable } from '@angular/core';
import { SharedService } from '../shared/shared.service';
@Injectable()
export class ArtistService {
constructor(private _sharedService: SharedService) {
}
共享服务.ts
import { Injectable, Inject } from '@angular/core';
import { Router } from '@angular/router';
import { Headers, Http, RequestOptions } from '@angular/http';
import { LoginService } from '../+login/login.service';
@Injectable()
export class SharedService {
constructor(@Inject(LoginService) private _loginService: LoginService,
private _router: Router, private _http: Http) { }
logoutUser(objectType: string, objectID: string) {
this._sharedService.logout();
}