Himanshi Gupta
Himanshi Gupta

Reputation: 171

How can call a function in service on click event in angular2?

This is the working plunker : http://plnkr.co/edit/FOJHofLSgLRB4Po5Li6B?p=preview . On clicking the classes the corresponding content at the bottom changes, but this is hardcoded & so is it possible to have something that makes the content to come from a service like this :

export class Subjectservice {
  getClass(id : number) : any {
    if(id==15)
      return [{label:  'Science', state: false},{label:  'Computer Science', state: false},{label:  'Social science', state: false},{label:  'Environmental Studies', state: false}];
    else if (id==68) 
      return [{label: 'English', state: false},{label:  'Hindi', state: false},{label:  'Mathematics', state: false},{label:  'Science', state: false}];
    else if (id==910) 
      return [{label: 'English', state: false},{label:  'Hindi', state: false}{label:  'Social science', state: false},{label:  'Sanskrit', state: false}];
    else
    return [{label: 'English', state: false}{label:  'Pol Science', state: false},{label:  'Comp Science', state: false},{label:  'Social science', state: false}];
  }
}

Upvotes: 1

Views: 1964

Answers (2)

Abdul Moiz Khan
Abdul Moiz Khan

Reputation: 703

I have a small angular 2 app created which is calling a service on click. Please see the source code here of Github. You can see the heroService.ts in app/services folder and heroes.component.ts.

Repository: https://github.com/khanstudio-github/Angular2AppASPNet/tree/master/Angular2StarterApp/Angular2StarterApp

I hope this would help you. Please feel free to ask if facing some issue.

Upvotes: 1

Ravinder Kumar
Ravinder Kumar

Reputation: 752

Create a service class:

import {Injectable} from '@angular/core';
@Injectable()
export class SubjectService{

getClass(id:any):number
{
//write your logic here....
}
}

Inject service in your AppComponent:

    import{SubjectService} from './subject.service';
            @Component({
            selector: 'my-app',
            template:'<div>.....</div>',
            providers:[SubjectService]
            })

    export class AppComponent
    {
        constructor(private subjectSer:SubjectService)
        {
            // now subjectSer can be used as instance of your service i.e. subjectSer.getClass(1);
        }
    }

Hope this will help you. Feel free to ask any question.

Upvotes: 0

Related Questions