• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Cancelling HTTP request when Angular Component destroyed

Sascha Оффлайн

Sascha

Заместитель Администратора
Команда форума
Администратор
Регистрация
9 Май 2015
Сообщения
1,483
Баллы
155

To cancel an ongoing HTTP request when a component is destroyed, you can use the following techniques:

  1. Using takeUntil operator:

import { Component, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

@Component({
selector: 'app-example',
template: '<p>Example Component</p>',
})
export class ExampleComponent implements OnDestroy {
private ngUnsubscribe = new Subject<void>();

constructor(private http: HttpClient) {
this.http.get('

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

') // making http call
.pipe(takeUntil(this.ngUnsubscribe)) // will subscribe to observanle until "ngUnsubscribe" is complete
.subscribe((response) => {
console.log(response);
});
}

ngOnDestroy(): void {
//marking ngUnsubscribe observable complete will unsubscribe the observable and request will get cancelled.
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}




2.Using Subscription object


import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Component({
selector: 'app-example',
template: '<p>Example Component</p>',
})
export class ExampleComponent implements OnDestroy {
private subscription: Subscription;

constructor(private http: HttpClient) {
this.subscription = this.http.get('

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

')
.subscribe((response) => {
console.log(response);
});
}

ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}





However this approach is good for a single subscription if we have (n) subscriptions and we want to cancel all on component destroy(which is good practice), follow solution 1.


Why is it important?

Canceling ongoing HTTP requests
when a component is destroyed is important to prevent memory leaks and improve the overall performance of your application. When a component is destroyed, any ongoing HTTP requests associated with that component should be cancelled to prevent unnecessary resource usage and potential errors.

📌📌 More Angular related topics here:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.





Источник:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу