2016-07-28 81 views
1

這是工作的重擊者:http://plnkr.co/edit/FOJHofLSgLRB4Po5Li6B?p=preview。 在點擊類底部的變化相應的內容,但這是硬編碼&所以是有可能有東西,使內容來自這樣的服務:如何在angular2中的click事件中調用一個函數?

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

回答

1

我有一個小角2應用程序創建,它是在點擊調用服務。請參閱Github的源代碼here。您可以看到heroService.ts應用程序/服務文件夾和heroes.component.ts

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

我希望這會幫助你。請隨時詢問是否面臨一些問題。

+0

在我的.html中,我有一個&在其點擊我想調用component.ts中的一個函數,它進一步調用service.ts中的函數。在從html中調用函數的同時,我也必須傳遞該卡的id,在此基礎上將從該服務返回一個特定的數組,並且因此我需要傳遞該id,不知何故我無法執行此操作... –

+1

這是你正在使用的相同代碼的工作調度器嗎?或者這是它的一些不同版本?上面提到的那個。 –

+0

這是相同的,不知何故,我用的角材料卡似乎不適用於笨拙的人,所以用粗體書寫的課程,你可以假設他們是卡 –

0

創建一個服務類:

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

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

進樣的服務:

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

希望這會幫助你。隨意問任何問題。

+0

謝謝,但我不知道,而調用subjectSer.getClass(ID);它給出的錯誤是它不能識別'id':[ts]找不到'id'的名字。任何 –