可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am creating a user model in typescript, with the following:
import {Inject} from 'angular2/core'; import {Http} from "angular2/http"; export class User { firstName:string; lastName:string; constructor(User:User, @Inject(Http) private _http){ this.firstName = User.firstName; this.lastName = User.lastName; } getUserFirstName(){ return this.firstName; } addUser(){ return this._http.post('/api/user/',this); } }
And in other places,I use:
var use = new User(userObject) // where userObject is an object with firstName and lastName
And this creates object, with two methods: getUsername
and addUser
.
However, there is an issue with injecting the http
. It is always undefined. Do you have any pointers or solutions to this problem?
Thanks
回答1:
If you want parameters injected to a class, you need to delegate instantiating to the injector. If you create an instance yourself with new SomeClass()
no injection will take place.
If you want a single instance you can just add the type to the providers and inject it.
bootstrap(AppComponent, [OtherProviders, HTTP_PROVIDERS, User]);
export class MyComponent { constructor(private user:User); }
If you want multiple instances (Angular DI creates singletons by default and always returns the same instance) you can use a factory.
@Injectable() export class User { firstName:string; lastName:string; constructor(User:User, @Inject(Http) private _http){ this.firstName = User.firstName; this.lastName = User.lastName; } getUserFirstName(){ return this.firstName; } addUser(){ return this._http.post('/api/user/',this); } } bootstrap(AppComponent, [OtherProviders, HTTP_PROVIDERS, provide(User, {useFactory: () => return (http) => new User(http);}, deps: [Http])]);
export class MyComponent { consturctor(@Inject(User) private userFactory) { user = this.userFactory(); } }
回答2:
To make injectable a class you need a decorator around it, the @Injectable
one. But in this case, Angular2 will instantiate the class by it own and provide it within the constructor of the class where you want to use it.
If you want to instantiate the class by yourself, you need to provide the dependency (in a service or in a component):
constructor(private http: Http) { } otherMethod() { var use = new User(userObject, this.http); }
You can remove the @Inject
decorator in this case from the User
class.