簡體   English   中英

在銷毀角度時調用 http 請求

[英]Call http request on destroy angular

http請求未執行

  @HostListener('window:beforeunload')
  async ngOnDestroy() {
    await this.microSitioService.cancelarTransaccion(this.tarjetaCreditoService.seguimientoEtapa).then(() => {});
  }

我需要在執行 on destroy 時執行 http 請求

編輯:修改后的答案

好的,這是當您想要確定調用 onDestroy 並停止導航時的格式,使用 $event 和 preventDefault。 我還添加了如何向瀏覽器返回消息以描述導航停止的原因。 您可以使用它來確保 http 請求按預期工作。

@HostListener('window:beforeunload', ['$event'])
async ngOnDestroy($event) {
  if (this.componentSub) {
    // handle unsubscriptions
    this.componentSub.unsubscribe();
  }

  await this.microSitioService
    .cancelarTransaccion(this.tarjetaCreditoService.seguimientoEtapa)
    .then(() => {});

  $event.preventDefault();
  $event.returnValue = 'A message.';
}

旁注:您是否將onDestroy作為類定義的一個實現?

import { Component, OnDestroy, HostListener } from '@angular/core';
class MyComponent implements onDestroy {

如果您正在尋找在 Angular 應用程序被銷毀時執行的事件,您可以使用具有OnDestroy()回調的PlatformRef

在 main.ts

function doSomethingOnAppDestory() {
  console.log('test');
}

platformBrowserDynamic().bootstrapModule(AppModule).then(ref => {

  // Ensure Angular destroys itself on hot reloads.
  if (window['ngRef']) {
    window['ngRef'].destroy();
  }
  window['ngRef'] = ref;

  ref.onDestroy(doSomethingOnAppDestory);

  // Otherwise, log the boot error
}).catch(err => console.error(err));

參見stackblitz 演示

暫無
暫無

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

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