2016-10-07 62 views
-1

我有一个名为ApiEndpoint的注入服务。我需要在另一个班级里使用这个服务,但是我面临的问题。注入一个服务到另一个类 - Angular2

的代码是这样的:

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

    constructor(private _http: Http) {} 

    createGroup() { this._http...) 
} 

//group.ts

import {ApiEndpoint} from './apiEndpoint'; 

    export class Group { 
    public name: string; 

    constructor(){} 

    save(){ 
     ApiEndpoint.createGroup(); <== ERROR 
    } 
    } 

很少有地方我们导入 'group.ts',然后执行以下

let myGroup = new Group(); 
myGroup.name = 'foo'; 
myGroup.save(); 

我收到以下错误:

Property 'createGroup' does not exist on type 'typeof ApiEndpoint'. 

我该如何解决?

回答

3

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(); 
相关问题