Html 如何在angular2中的click事件中调用服务中的函数?

Html 如何在angular2中的click事件中调用服务中的函数?,html,angular,angular2-services,Html,Angular,Angular2 Services,这是正在工作的plunker:。 单击类时,底部的相应内容会发生变化,但这是硬编码的&因此,是否有可能使内容来自这样的服务: export class Subjectservice { getClass(id : number) : any { if(id==15) return [{label: 'Science', state: false},{label: 'Computer Science', state: false},{label: 'Social sc

这是正在工作的plunker:。 单击类时,底部的相应内容会发生变化,但这是硬编码的&因此,是否有可能使内容来自这样的服务:

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

创建服务类:

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

getClass(id:any):number
{
//write your logic here....
}
}
在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);
        }
    }
从“/subject.service”导入{SubjectService};
@组成部分({
选择器:“我的应用程序”,
模板:“…”,
提供者:[主题服务]
})
导出类AppComponent
{
构造函数(私有subjectSer:SubjectService)
{
//现在subjectSer可以用作您的服务实例,即subjectSer.getClass(1);
}
}

希望这对你有帮助。请随便问任何问题。

我创建了一个angular 2应用程序,它可以在单击时调用服务。请参阅Github的源代码。您可以在app/services文件夹中查看heroService.tsheros.component.ts

存储库


我希望这对你有帮助。请随时询问是否面临一些问题。

在my.html中,我有一个&单击它,我想调用component.ts中的一个函数,它进一步调用service.ts中的一个函数。在从html调用函数时,我还必须传递卡的id,根据该id,服务将返回一个特定的数组,因此我需要传递id,不知何故我无法执行此操作…这是一个与您正在使用的代码相同的工作插件吗?或者这是它的不同版本?你上面提到的那张。这是一样的,不知怎么的,我正在使用的棱角材质卡在plunker上似乎不起作用,所以用粗体写的类,你可以假设它们是卡片,而不是像这样调用click(单击)=“view='one'”。使用一个函数,比如(单击)=“checkView('one')”。您的AppComponent类使用此参数调用您的服务,即1。请参阅
app/components/heros
文件夹中的dashboard.component.ts文件。您需要在checkView函数上像这样调用服务,因为我在ngOnInit()中调用了服务组件,不用担心,这只是从结果集中挑选服务返回的前5条记录。在您的情况下,这类似于
。然后(serviceData=>this.resultHtml=serviceData)
。然后()
只是一个承诺回调,意味着它只会在您的服务返回一些结果时运行。若服务以某种方式失败,这将被忽略。谢谢,但我不知道调用subjectSer.getClass(id);它给出了一个无法识别“id”的错误:[ts]找不到名称“id”。任何