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

is it possible to call a function from service in onclick event in angular 4

我在服务 'data.service.ts' 中编写了一个方法 getDataMethod()。我想在有人点击 html 页面上的提交按钮时调用此函数。

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

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中采用另一种方法,看看官方文档)然后将其注入到你的组件中,然后你可以在 clicksubmit 事件中使用它。

组件(.ts)文件:

export class TestComponent {
    constructor(public testService: TestService) {
    }
}

模板 (.html) 文件:

<button (click)="testService.getDataService()">Button</button>

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

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

查看 this stackblitz POC,其中还展示了如何在模块中导入创建的服务,然后才能将其注入组件。

Service

import { Injectable } from '@angular/core';

@Injectable()
export class Service {

  public getData(): string {
    return "Data From Service";
  }
}

Module

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

Component

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

}

HTML

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

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

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