Angular2测试依赖注入 [英] Angular2 Beta dependency injection

查看:190
本文介绍了Angular2测试依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个加载QApi服务的NavBar组件,该QApi加载服务将UserService,但我得到了以下错误:

I have a NavBar Component which loads the QApi Service, the QApi Service loads the UserService, but I get the following error:

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

无论是我根本没有得到依赖注入的概念,我犯了一个愚蠢的错误,或相对于本地开发这只是方式复杂...感谢您的帮助。

Either I simply don't get the concept of dependency injection, I made a stupid error, or this is just way to complicated compared to native development... Thanks for your help.

下面我code:

UserService:

UserService:

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

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

QApi服务:

QApi Service:

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

@Injectable() 
export class QApi {

constructor(private _userService: UserService) {}

}

的NavBar组件:

NavBar Component:

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

First of all: Thanks for alle the great answers each and every single one helped me to understand dependency injection better, especially this article: https://angular.io/docs/ts/latest/guide/hierarchical-dependency-injection.html

我改变了我的QApi类这样的:

I changed my QApi class to this:

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);
}

}

现在它像我希望的那样。广东话感谢你们!够

Now it works like I hoped it would. Cant thank you guys enough!!

推荐答案

添加 UserService 的组件提供商

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

下面就是两个很好的文章,以更好地了解Angular2依赖注入:

Here are two good articles to better understand Angular2 Dependency Injection:

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

这篇关于Angular2测试依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆