在创建打字稿模式,采取注射剂 [英] Creating models in typescript that take injectables
问题描述
我创建的打字稿用户模型,具有以下内容:
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);
}
}
和在其他地方,我用:
var use = new User(userObject) // where userObject is an object with firstName and lastName
和这将创建对象,用两种方法: getUsername
和 ADDUSER
And this creates object, with two methods: getUsername
and addUser
.
不过,与注射 HTTP
的问题。它总是不确定的。你有任何指针或解决这个问题?
However, there is an issue with injecting the http
. It is always undefined. Do you have any pointers or solutions to this problem?
感谢
推荐答案
如果你想注入类的参数,你需要委托实例的注射器。如果你自己创建一个实例新SomeClass的()
没有注入会发生。
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);
}
如果你想多个实例(DI角默认创建单身,总是返回相同的实例),可以使用一个工厂。
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();
}
}
这篇关于在创建打字稿模式,采取注射剂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!