Angular 2:将服务传递给班级

时间:2017-03-23 14:51:08

标签: angular typescript

我有一个服务从API获取一些数据并返回一个具有值为Company[]的键的对象,它看起来像这样:

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

我的company.model.ts看起来像这样:

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....
}

在我的公司模型中,我希望有一些方法可以更改Company对象的属性并将此更改与服务器进行通信。

我很难理解如何将CompanyService Injectable传递到Company课程,特别是因为新公司几乎只能在CompanyService本身创建。

如果我能提供进一步的说明或代码,请告诉我。

谢谢!

1 个答案:

答案 0 :(得分:1)

如果您在CompanyService中提供了app.module,那么您将在整个申请过程中使用一个实例。

app.module.ts

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

要将其放入Company,您可以这样做:

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将从您的根目录中注入CompanyService的实例

你可以在这里阅读:

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

相关问题