Creating models in typescript that take injectables

匿名 (未验证) 提交于 2019-12-03 09:14:57

问题:

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.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!