Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Beta dependency injection

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.

Here my code:

UserService:

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

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

QApi Service:

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

@Injectable() 
export class QApi {

constructor(private _userService: UserService) {}

}

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

EDIT:

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

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!!

like image 361
jona jürgen Avatar asked Feb 14 '26 13:02

jona jürgen


1 Answers

Add UserService to the component providers:

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

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
like image 196
alexpods Avatar answered Feb 17 '26 03:02

alexpods



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!