[英]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.