uksz
uksz

Reputation: 18699

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);
    }
}

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

Upvotes: 1

Views: 1455

Answers (2)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657426

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();
  }
}

Upvotes: 4

Thierry Templier
Thierry Templier

Reputation: 202196

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.

Upvotes: 1

Related Questions