是否可以在角度4

时间:2018-06-13 09:42:32

标签: angular angular-services

我是角度为4的新蜜蜂。我在我的服务&data; service.service.ts'中编写了一个方法getDataMethod()。

现在我想在我的html页面点击一个提交按钮时调用这个函数。

我们怎么称呼这个功能?请帮帮我。

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

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

3 个答案:

答案 0 :(得分:4)

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

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


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

答案 1 :(得分:1)

您需要向父模块或组件本身提供服务(您可以在角度v6中采用另一种方法,查看官方文档)然后将其注入组件,然后您可以在{{{ 1}}或click事件。

组件(.ts)文件:

submit

模板(.html)文件:

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

虽然从组件内部声明的方法调用service方法会更好。

答案 2 :(得分:0)

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

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

  

服务

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

}
  

HTML

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

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

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