Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency injection with optional parameter in Angular2

I have multiple components which require the same dependency which requires a string for the constructor. How can I tell angular2 to use a specific instance of the type for DI?

For example:

ChatUsers.ts:

@Component({
    selector: "chat-users"
})
@View({
    directives: [],
    templateUrl: '/js/components/ChatUsers.html'
})
export class ChatUsers {

    constructor(public currentUser : User) {
    }
}

and app.ts:

/// <reference path="../libs/typings/tsd.d.ts" />

import {Component, View, bootstrap} from 'angular2/angular2';

import {User} from "User";

// How to create a user, e.g. new User('John') and use it for DI?

@Component({
    selector: 'chat-app'
})
@View({
    directives: [ ],
    template: `
      <div> Some text
      </div>`
})
class ChatApp {
    constructor(public user: User) {
        // do something with user
    }


}
bootstrap(ChatApp, [ User ]);

User.ts

export class User {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
}

If run this code, the error is:

Cannot resolve all parameters for User(?). Make sure they all have valid type or annotations.

I'm using the most recent angular2 version: 2.0.0-alpha.44

like image 718
Stefan Profanter Avatar asked Oct 29 '15 15:10

Stefan Profanter


1 Answers

To make dependency optional just use @Optional parameter decorator (see this plunker):

class User {
  name: string;
  constructor(@Optional() name: string) {
    this.name = name;
  }
}

If you want to inject name into User you have two solutions:

  1. Add some 'userName' provider to app providers and use @Inject('userName') parameter decorator to inject it into User (see this plunker).
class User {
  name: string;
  constructor(@Inject('userName') name: string) {
      this.name = name;
  }
}
// ...
bootstrap(ChatApp, [
  User, 
  provide('userName', { useValue: 'Bob'})
]);
  1. Use useFactory to specifically instantiate your user (see this plunker):
bootstrap(ChatApp, [
  provide(User, { useFactory: () => new User('John') })
]);
like image 103
alexpods Avatar answered Oct 13 '22 01:10

alexpods