是否可以在angular 4中的onclick事件中从服务调用函数

是否可以在angular 4中的onclick事件中从服务调用函数,angular,angular-services,Angular,Angular Services,我已经在服务“data.service.ts”中编写了一个getDataMethod()方法。我想在有人从html页面单击submit按钮时调用此函数 我在组件的构造函数中创建了一个服务实例,如下所示: cnstructor(private dataservice: DataService){ this.data-service-method = this.dataservice.getDataMethod(); } 如何调用此函数?您需要在组件的构造函数中创建服务的实例,然后引用服务

我已经在服务“data.service.ts”中编写了一个getDataMethod()方法。我想在有人从html页面单击submit按钮时调用此函数

我在组件的构造函数中创建了一个服务实例,如下所示:

cnstructor(private dataservice: DataService){
    this.data-service-method = this.dataservice.getDataMethod();
}

如何调用此函数?

您需要在组件的构造函数中创建服务的实例,然后引用服务并调用方法

import { DataService } from './data.service';


export Class ComponentA { 
 constructor(public dataService: DataService) { } 
 myFunct(){
   this.dataService.getDataService().subscribe();
}
}

您需要向父模块或组件本身提供服务(您可以在angular v6中采用另一种方法,查看官方文档),然后将其注入到组件中,然后您可以在
单击
提交
事件中使用它

组件(.ts)文件:

模板(.html)文件:

按钮

尽管从组件内部声明的方法调用服务方法更好。

正如@Sajeetharan已经提到的,您必须从组件调用服务

查看该示例,它还显示了在将创建的服务注入组件之前如何在模块中导入该服务

服务

模块

组成部分

HTML


获取数据
来自服务的数据-{data}


我们不能直接调用服务方法而不在组件中创建实例吗?什么是“getDataService()”?Angular告诉我,它需要一个参数。
export class TestComponent {
    constructor(public testService: TestService) {
    }
}
<button (click)="testService.getDataService()">Button</button>
import { Injectable } from '@angular/core';

@Injectable()
export class Service {

  public getData(): string {
    return "Data From Service";
  }
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { Service } from './service'

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, HelloComponent ],
  providers: [Service],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }
import { Component } from '@angular/core';
import { Service } from './service'

@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    name = 'Angular 6';

    public data: string;

    constructor(private _Service: Service) {

    }

    public getData(): void {
        this.data = this._Service.getData();
    }

}
<hello name="{{ name }}"></hello>

<button (click)="getData()">get data</button>

<p> data from service - {{data}} </p>