将服务注入另一个类-Angular2

将服务注入另一个类-Angular2,angular,Angular,我有一个名为Apident的可注入服务。我需要在另一个类中使用此服务,但是我面临一些问题 代码是这样的: //apiEndpoint.ts @Injectable() export class ApiEndpoint { constructor(private _http: Http) {} createGroup() { this._http...) } //组.ts import {ApiEndpoint} from './apiEndpoint'; export cl

我有一个名为Apident的可注入服务。我需要在另一个类中使用此服务,但是我面临一些问题

代码是这样的:

//apiEndpoint.ts
@Injectable()
export class ApiEndpoint {

  constructor(private _http: Http) {}

  createGroup() { this._http...) 
}
//组.ts

import {ApiEndpoint} from './apiEndpoint';

  export class Group {
    public name: string;

    constructor(){}

    save(){
       ApiEndpoint.createGroup();  <== ERROR
    }
  }
我收到以下错误:

Property 'createGroup' does not exist on type 'typeof ApiEndpoint'.
如何解决此问题?

createGroup()
是一个实例方法,您试图将其用作静态方法。使用依赖项注入:

export class Group {
    public name: string;

    constructor(private apiEndpoint; ApiEndpoint ){}

    save() {
       this.apiEndpoint.createGroup();
    }
}

@Injectable()
export class GroupFactory {
    constructor(private apiEndpoint: ApiEndpoint) {}

    createGroup() {
        return new Group(this.apiEndpoint);
    }
}
然后将GroupFactory注入需要创建组的组件中,并使用

let myGroup = this.groupFactory.createGroup();
myGroup.name = 'foo';
myGroup.save();
let myGroup = this.groupFactory.createGroup();
myGroup.name = 'foo';
myGroup.save();