Skip to content

Instantly share code, notes, and snippets.

@navix
Forked from xtianjohns/component_takeUntil.ts
Created June 14, 2017 11:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save navix/b65eb82fc27efaa142d7d7e1bf78716f to your computer and use it in GitHub Desktop.
Save navix/b65eb82fc27efaa142d7d7e1bf78716f to your computer and use it in GitHub Desktop.
takeUntil for fun and for profit
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { MyService } from './MyService.ts';
import 'rxjs/add/operator/takeUntil';
@Component({
selector: 'my-rad-component',
})
export class MyComponent implements OnInit, OnDestroy {
/* A subject for monitoring the destruction of the component. */
private destroyed$: Subject<{}> = new Subject();
/* Inject a service with an observable API. */
constructor(private myService: MyService) { }
ngOnInit() {
this.myService.getData() /* Fetch some data. */
.takeUntil( this.destroyed$ ) /* Unsubscribe from the stream upon destruction. */
.subscribe( data => {
// do something with your data, AKA: define your effects.
});
}
ngOnDestroy() {
this.destroyed$.next(); /* Emit a notification on the subject. */
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment