简体   繁体   中英

Injecting a service into another class - Angular2

I have a injectable service called ApiEndpoint. I need to use this service inside of another class, however i am facing issues.

The code goes something like this:

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

Few places we import 'group.ts' and do the following

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

I receive the following error:

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

How do I resolve this ?

createGroup() is an instance method, and you're trying to use it as a static method. Use dependency injection:

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

Then inject GroupFactory in components that need to create groups, and use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM