[英]Button click event is not reponding in Angular
在 my.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";
}
}
当我单击“数据导入”按钮时……什么都没有发生,也没有生成任何事件。
1-第二行不会被执行,因为第一条语句有一个返回关键字:
return this.http.get(this.baseUrl);
this.etext="The operation has been done";
2- 正如 Martin Čuka 在下面评论的那样,您需要subscribe
httpclient 返回的 Observable。
this.downloadService.getDownload().subscribe(resp => { // do whatever });
什么都没有发生,因为 httpClient 正在返回 Observable 你需要订阅它。 添加订阅到您的服务
this.downloadService.getDownload().subscribe();
至于线
this.etext="The operation has been done";
编译器会告诉你它无法访问,但真正的问题在于缺少订阅
export class Component {
constructor(private downloadService: DownloadService){}
download(){
this.downloadService.getDownload().subscribe(
() => {
// success code
},
(error) => {
// error code
}
);
}
}}
我认为 http 请求被触发。 但是,您不知道它何时完成,因为您没有订阅 http.get 返回的 Observable。
组件.ts
export class Component {
constructor(private downloadService: DownloadService){}
download(){
this.downloadService.getDownload().subscribe(
() => {
// success code
},
(error) => {
// error code
}
);
}
}
订阅时要小心,订阅完成后您必须取消订阅。 https://blog.angularindepth.com/the-best-way-to-unsubscribe-rxjs-observable-in-the-angular-applications-d8f9aa42f6a0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.