簡體   English   中英

在 Angular 服務的 OnDestroy 掛鈎中取消訂閱 HTTP 客戶端調用

[英]Unsubscribing to HTTP client call in OnDestroy hook of Angular Service

有沒有辦法從 angular 服務 onDestroy 取消訂閱 http 調用。

PS 我知道 rxjs 'take' 運營商或取消訂閱組件本身的服務。

    import { HttpClient } from "@angular/common/http";
import { Injectable, OnDestroy } from "@angular/core";

@Injectable()
export class SampleService implements OnDestroy {
  constructor(private httpClient: HttpClient) {}

  getSampleData() {
    return this.httpClient.get("https://jsonplaceholder.typicode.com/todos/1");
  }
  ngOnDestroy(): void {
    // automatically unsubscribe to service.
  }
}

服務沒有 UI 驅動的生命周期,因此無論您如何實現onDestroy ,除非您自己手動調用它,否則它永遠不會被調用。

這就是為什么我們有工具,讀取 API,比如:

<div> {{ yourObservable$ | async | json }} </div>
@Component({...})
export class Component implements OnInit {
   yourObservable$: Observable<any>
   constructor(public yourService: TheService) {
       this.yourObservable$ = this.yourService.getSampleData()
   }
}

異步 pipe 通知生命周期更改,並在組件被刪除時自動訂閱和取消訂閱

  • 訂閱(您可以通過調用 .add 添加其他.add )並在組件的onDestroy調用subscription.unsubscribe()

Subscription.unsubscribe 是 async pipe 的基礎,你也可以自己使用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM