首页 > 解决方案 > Angular 中的按钮单击事件没有响应

问题描述

在我的 .html 文件中,我有以下代码:- 此处出现按钮数据导入...。

<button mat-menu-item (click)="download()">
                <mat-icon>cloud_download</mat-icon>
                <span>Data Import</span>
</button>

在component.ts文件中:-
在这里我定义了单击按钮后要调用的函数::

  constructor(
           private downloadService: DownloadService
      )

    download(){
      this.downloadService.getDownload();

      }

在 downloadservice.ts 文件中:-

这里已经创建了服务,它将在后端调用 api /Download。

 export class DownloadService {
     etext : String;
    baseUrl: string = environment.apiUrl + '/Download';
      constructor(private http: HttpClient) { }

      getDownload() {
        return this.http.get(this.baseUrl);
        this.etext="The operation has been done";
      }
      }

当我单击“数据导入”按钮时……什么都没有发生,也没有生成任何事件。

标签: javascriptangulartypescript

解决方案


1-第二行不会被执行,因为第一条语句有一个返回关键字:

return this.http.get(this.baseUrl);
this.etext="The operation has been done";

2- 正如 Martin Čuka 在下面评论的那样,您需要subscribehttpclient 返回的 Observable。

this.downloadService.getDownload().subscribe(resp => { // do whatever });

推荐阅读