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
  • Select an option

  • Save navix/b65eb82fc27efaa142d7d7e1bf78716f to your computer and use it in GitHub Desktop.

Select an option

Save navix/b65eb82fc27efaa142d7d7e1bf78716f to your computer and use it in GitHub Desktop.

Revisions

  1. @xtianjohns xtianjohns renamed this gist Jun 4, 2017. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. @xtianjohns xtianjohns revised this gist Jun 4, 2017. 1 changed file with 6 additions and 4 deletions.
    10 changes: 6 additions & 4 deletions component.ts
    Original file line number Diff line number Diff line change
    @@ -10,20 +10,22 @@ import 'rxjs/add/operator/takeUntil';
    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()
    .takeUntil( this.destroyed$ )
    this.myService.getData() /* Fetch some data. */
    .takeUntil( this.destroyed$ ) /* Unsubscribe from the stream upon destruction. */
    .subscribe( data => {
    // do something with your data
    // do something with your data, AKA: define your effects.
    });
    }

    ngOnDestroy() {
    this.destroyed$.next();
    this.destroyed$.next(); /* Emit a notification on the subject. */
    }
    }
  3. @xtianjohns xtianjohns revised this gist Jun 4, 2017. No changes.
  4. @xtianjohns xtianjohns created this gist Jun 4, 2017.
    29 changes: 29 additions & 0 deletions component.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    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();

    constructor(private myService: MyService) { }

    ngOnInit() {
    this.myService.getData()
    .takeUntil( this.destroyed$ )
    .subscribe( data => {
    // do something with your data
    });
    }

    ngOnDestroy() {
    this.destroyed$.next();
    }
    }