nick
nick

Reputation: 3711

Angular 2: Pass Service to Class

I have a service that gets some data from an API and returns an object which has a key of value Company[], it looks like this:

getCompanies(){
    return this.authHttp.get(this._companiesUrl)
        .map(res => {
            let response = res.json() || [];
                response.items = response.items.map(thing => new Company(thing) );
                return response;
            });
}

My company.model.ts looks like this:

export class Company{

id: number;
....
constructor(obj:any){
    ....
}

// I'd like to be able to do this:
changeName(newName: string){
    this.companyService.changeName(this.id, newName).sub....
}

In my company model I'd like to have some methods that would change the Company object's property and communicate this changes with the server.

I'm struggle to understand how to pass the CompanyService Injectable into the Company class, especially since new companies will almost exclusively be created in the CompanyService itself.

Please let me know if I can provide further clarification or code.

Thanks!

Upvotes: 0

Views: 937

Answers (1)

Borquaye
Borquaye

Reputation: 776

If you provide CompanyService in your app.module you will have one instance of it to use throughout your application.

In app.module.ts:

import { CompanyService } from 'whereEverThisFileIs'
...
@NgModule({
  imports: [...],
  declarations: [...],
  providers: [..., CompanyService],
  ...
})

To get it inside Company you would do this:

import { CompanyService } from 'whereEverThisFileIs'

export class Company{
  id: number;
....
constructor(obj:any, private _companyService: CompanyService){
....
}

changeName(newName: string){
  this._companyService.changeName(this.id, newName).sub....
}

Angular will inject the instance of CompanyService from the root for you

You can read about this here:

https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#angular-dependency-injection

Upvotes: 1

Related Questions