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
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:
'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'})
]);
useFactory
to specifically instantiate your user (see this plunker):bootstrap(ChatApp, [
provide(User, { useFactory: () => new User('John') })
]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With