依赖注入 – Angular2 Beta依赖注入

我有一个加载QApi服务的NavBar组件,QApi服务加载UserService,但是我收到以下错误:

EXCEPTION: No provider for UserService! (NavBarComponent -> QApi -> UserService)

要么我根本没有得到依赖注入的概念,我犯了一个愚蠢的错误,或者这只是复杂的方式与本机开发相比…感谢您的帮助.

这是我的代码:

UserService:

import {Injectable} from 'angular2/core';
//import {User} from '../data-source-mocks/users';

@Injectable() 
export class UserService {
 public isAuthenticated = true;
}

QApi服务:

import {Injectable} from 'angular2/core';
import {UserService} from '../user/user.service';

@Injectable() 
export class QApi {

constructor(private _userService: UserService) {}

}

NavBar组件:

import {Component} from 'angular2/core';
import {QApi} from '../../services/q-api/q-api';

@Component({
 selector: 'nav-bar',
 template: `Test NavBar`,
 providers: [QApi]
})

export class NavBarComponent {
private _isAuthenticated = false;

constructor(private _QApi: QApi) {}
}

编辑:

首先:感谢你们给出了很好的答案,每一个人都帮助我更好地理解依赖注入,尤其是这篇文章:https://angular.io/docs/ts/latest/guide/hierarchical-dependency-injection.html

我将我的QApi课改为:

import {Injectable, Inject, Injector} from 'angular2/core';
import {UserService} from '../user/user.service';
import {CardService} from '../card/card.service';

@Injectable()
export class QApi {

constructor() {
    var _injector = Injector.resolveAndCreate([UserService, 
                                               CardService]);

    this.userService = _injector.get(UserService);
    this.cardService = _injector.get(CardService);
}

}

现在它的工作方式就像我希望的那样.不能谢谢你们!

最佳答案
将UserService添加到组件提供者:

@Component({
    selector: 'nav-bar',
    template: `Test NavBar`,
    providers: [QApi, UserService] // <- add UserService here
})
export class NavBarComponent { /* ... */ }

这里有两篇很好的文章来更好地理解Angular2依赖注入:

> blog.thoughtram.io: Dependency Injection in Angular2
> blog.thoughtram.io: Injecting services in services in Angular 2

转载注明原文:依赖注入 – Angular2 Beta依赖注入 - 代码日志