Home Web Front-end JS Tutorial A brief discussion on unsubscribing in Angular

A brief discussion on unsubscribing in Angular

Jan 16, 2018 am 09:02 AM
angular Cancel subscription

This article mainly introduces a brief discussion on when to cancel a subscription in Angular. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

You may know that when you subscribe to an Observable object or set up an event listener, at some point in time, you need to perform an unsubscription operation to release the operating system's memory. Otherwise, your application may suffer from memory leaks.

Next let's take a look at some common scenarios where unsubscription operations need to be performed manually in the ngOnDestroy life cycle hook.

Manual release resource scenario

Form


export class TestComponent {

 ngOnInit() {
  this.form = new FormGroup({...});
  // 监听表单值的变化
  this.valueChanges = this.form.valueChanges.subscribe(console.log);
  // 监听表单状态的变化              
  this.statusChanges = this.form.statusChanges.subscribe(console.log);
 }

 ngOnDestroy() {
  this.valueChanges.unsubscribe();
  this.statusChanges.unsubscribe();
 }
}
Copy after login

The above scheme also applies to Other form controls.

Routing


export class TestComponent {
 constructor(private route: ActivatedRoute, private router: Router) { }

 ngOnInit() {
  this.route.params.subscribe(console.log);
  this.route.queryParams.subscribe(console.log);
  this.route.fragment.subscribe(console.log);
  this.route.data.subscribe(console.log);
  this.route.url.subscribe(console.log);
  
  this.router.events.subscribe(console.log);
 }

 ngOnDestroy() {
  // 手动执行取消订阅的操作
 }
}
Copy after login

Renderer Service


##

export class TestComponent {
 constructor(
  private renderer: Renderer2, 
  private element : ElementRef) { }

 ngOnInit() {
  this.click = this.renderer
    .listen(this.element.nativeElement, "click", handler);
 }

 ngOnDestroy() {
  this.click.unsubscribe();
 }
}
Copy after login

Infinite Observables


When you use the interval() or fromEvent() operator, you create an infinite Observable object. In this case, when we no longer need to use them, we need to unsubscribe and release the resources manually.


export class TestComponent {
 constructor(private element : ElementRef) { }

 interval: Subscription;
 click: Subscription;

 ngOnInit() {
  this.interval = Observable.interval(1000).subscribe(console.log);
  this.click = Observable.fromEvent(this.element.nativeElement, 'click')
              .subscribe(console.log);
 }

 ngOnDestroy() {
  this.interval.unsubscribe();
  this.click.unsubscribe();
 }
}
Copy after login

Redux Store



export class TestComponent {

 constructor(private store: Store) { }

 todos: Subscription;

 ngOnInit() {
   /**
   * select(key : string) {
   *  return this.map(state => state[key]).distinctUntilChanged();
   * }
   */
   this.todos = this.store.select('todos').subscribe(console.log); 
 }

 ngOnDestroy() {
  this.todos.unsubscribe();
 }
}
Copy after login

No need to manually release resource scenarios

AsyncPipe


@Component({
 selector: 'test',
 template: `<todos [todos]="todos$ | async"></todos>`
})
export class TestComponent {
 constructor(private store: Store) { }
 
 ngOnInit() {
   this.todos$ = this.store.select(&#39;todos&#39;);
 }
}
Copy after login

When the component is destroyed, the async pipeline will automatically perform the unsubscription operation to avoid memory Risk of leakage.

Angular AsyncPipe source code snippet


@Pipe({name: &#39;async&#39;, pure: false})
export class AsyncPipe implements OnDestroy, PipeTransform {
 // ...
 constructor(private _ref: ChangeDetectorRef) {}

 ngOnDestroy(): void {
  if (this._subscription) {
   this._dispose();
  }
 }
}
Copy after login

@HostListener



export class TestDirective {
 @HostListener(&#39;click&#39;)
 onClick() {
  ....
 }
}
Copy after login

Things to note Yes, if you use the @HostListener decorator, we cannot manually unsubscribe when adding event listeners. If you need to manually remove event monitoring, you can use the following method:


// subscribe
this.handler = this.renderer.listen(&#39;document&#39;, "click", event =>{...});

// unsubscribe
this.handler();
Copy after login

Finite Observable

When you You also don't need to manually unsubscribe when using an HTTP service or timer Observable object.


export class TestComponent {
 constructor(private http: Http) { }

 ngOnInit() {
  // 表示1s后发出值,然后就结束了
  Observable.timer(1000).subscribe(console.log);
  this.http.get(&#39;http://api.com&#39;).subscribe(console.log);
 }
}
Copy after login

timer operator

Operator signature


Copy code The code is as follows:

public static timer(initialDelay: number | Date, period: number, scheduler: Scheduler): Observable

Operator function


timer return An Observable that emits an infinite incrementing sequence with a certain time interval, which is chosen by you.

Operator examples



// 每隔1秒发出自增的数字,3秒后开始发送
var numbers = Rx.Observable.timer(3000, 1000);
numbers.subscribe(x => console.log(x));

// 5秒后发出一个数字
var numbers = Rx.Observable.timer(5000);
numbers.subscribe(x => console.log(x));
Copy after login

Final suggestion


You should call the unsubscribe() method as little as possible , you can learn more about Subject in this article RxJS: Don't Unsubscribe.

Specific examples are as follows:


export class TestComponent {
 constructor(private store: Store) { }

 private componetDestroyed: Subject = new Subject();
 todos: Subscription;
 posts: Subscription;

 ngOnInit() {
   this.todos = this.store.select(&#39;todos&#39;)
           .takeUntil(this.componetDestroyed).subscribe(console.log); 
           
   this.posts = this.store.select(&#39;posts&#39;)
           .takeUntil(this.componetDestroyed).subscribe(console.log); 
 }

 ngOnDestroy() {
  this.componetDestroyed.next();
  this.componetDestroyed.unsubscribe();
 }
}
Copy after login

takeUntil operator

Operator signature



public takeUntil(notifier: Observable): Observable<T>
Copy after login

Operator function


Emits the value emitted by the source Observable until the notifier Observable emits the value.

Operator examples



var interval = Rx.Observable.interval(1000);
var clicks = Rx.Observable.fromEvent(document, &#39;click&#39;);
var result = interval.takeUntil(clicks);

result.subscribe(x => console.log(x));
Copy after login
Related recommendations:


node.js publish-subscribe mode Method

Detailed explanation of JavaScript publish-subscribe mode usage

PHP WeChat public platform development Subscription event processing_PHP tutorial

The above is the detailed content of A brief discussion on unsubscribing in Angular. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to cancel window overlay and cascading effects in Win11 How to cancel window overlay and cascading effects in Win11 Jan 10, 2024 pm 02:50 PM

The default window overlapping in win11 is very annoying, so many friends want to cancel the overlapping windows, but don’t know how to cancel it. In fact, we only need to use relevant software. How to cancel overlapping windows in win11 Method 1: Cancel through the taskbar 1. Win11 does not have its own cancellation function, so we need to download a "startallback" 2. After the download is completed, "unzip" the compressed package. After the decompression is completed, open folder, run the illustrated installation program to complete the installation. . 3. After the installation is completed, you need to open the "Control Panel" and then change the "View by" in the upper right corner to "Large Icons". 4. In this way, you can find "startallback", click to open it, and enter the "Tasks" on the left

Tutorial to cancel win11 screen lock Tutorial to cancel win11 screen lock Dec 31, 2023 pm 12:29 PM

In order to protect the screen content or save power, we often turn on the screen saver, but find it very troublesome to re-enter the password lock every time after exiting the screen saver. So how to cancel the win11 screen lock? In fact, it can be turned off in the screen saver settings. How to cancel the win11 screen lock: 1. First, we right-click a blank space on the desktop and open "Personalization" 2. Then find and open the "Lock Screen Interface" on the right 3. Then open the "Screen Saver" in the relevant settings at the bottom 4. Finally, check "Show login screen on restore" and confirm to save to cancel the screen lock.

How to cancel an order with Meituan How to cancel an order with Meituan Mar 07, 2024 pm 05:58 PM

When placing orders using Meituan, users can choose to cancel the orders they do not want. Many users do not know how to cancel Meituan orders. Users can click on the My page to enter the order to be received, select the order that needs to be canceled and click Cancel. How to cancel an order with Meituan 1. First, click on Meituan My Page to enter the order to be received. 2. Then click to enter the order that needs to be canceled. 3. Click Cancel Order. 4. Click OK to cancel the order. 5. Finally, select the reason for cancellation according to your personal situation and click Submit.

Detailed steps to cancel the ear symbol on WeChat Detailed steps to cancel the ear symbol on WeChat Mar 25, 2024 pm 05:01 PM

1. The ear symbol is the voice receiver mode. First, we open WeChat. 2. Click me in the lower right corner. 3. Click Settings. 4. Find the chat and click to enter. 5. Uncheck Use earpiece to play voice.

Where to cancel Mango TV automatic renewal? Where to cancel Mango TV automatic renewal? Feb 28, 2024 pm 10:16 PM

When many users experience Mango TV, a video software, they choose to become members in order to enjoy more film and television resources and more comprehensive services. In the process of using Mango TV membership services, some users will choose to turn on the automatic renewal function to enjoy the discounts to ensure that they will not miss any exciting content. However, when users no longer need membership services or want to change the payment method, canceling the automatic renewal function is a very important thing to protect the safety of property. How to cancel the automatic renewal service of Mango TV? Users who want to know Come and follow this article to learn more! How to cancel the automatic renewal of membership on Mango TV? 1. First enter [My] in the Mango TV mobile APP, and then select [VIP Membership]. 2. Then find [Tube

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

How to cancel automatic renewal on iQiyi How to cancel automatic renewal on iQiyi How to cancel automatic renewal on iQiyi How to cancel automatic renewal on iQiyi Feb 22, 2024 pm 04:46 PM

You can open the management automatic renewal function on the My Gold VIP Member interface to cancel. Tutorial Applicable Model: Huawei P50 System: HarmonyOS2.0 Version: iQiyi 12.1.0 Analysis 1 Open the iQiyi app on your phone, and then enter the My page. 2 Then click Gold VIP Membership at the top of my page, and then click Manage Automatic Renewal Options. 3. Click Cancel automatic renewal in the pop-up window. If you are not interested, continue to cancel. 4Finally confirm to turn off automatic renewal and click I understand, just reject it cruelly. Supplement: How to cancel the automatic renewal function of iQiyi on Apple mobile phone 1. Open the settings on the phone, and then click [AppleID] at the top of the settings interface. 2Click [Subscribe] on the AppleID interface to select

Operation steps for canceling subscription payment on WeChat Operation steps for canceling subscription payment on WeChat Mar 26, 2024 pm 08:21 PM

1. Click the [iTunesStore and AppStore] option in the phone settings. 2. Click [View AppleID], and then enter the login password. 3. Enter the [Account Settings] interface and click [Payment Information]. 4. Check the payment method as [None] and click [Finish]. After completion, return to the WeChat interface. At this time, you will receive the [Successful Cancellation Notification] message, and WeChat will no longer automatically deduct fees.

See all articles