Snippets Collections
import { Component, OnDestroy, OnInit } from '@angular/core';
// RxJs 6.x+ import paths
import { filter, startWith, takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { BookService } from '../books.service';

@Component({
    selector: 'app-books',
    templateUrl: './books.component.html'
})
export class BooksComponent implements OnDestroy, OnInit {
    private ngUnsubscribe = new Subject<void>();

    constructor(private booksService: BookService) { }

    ngOnInit() {
        this.booksService.getBooks()
            .pipe(
               startWith([]),
               filter(books => books.length > 0),
               takeUntil(this.ngUnsubscribe)
            )
            .subscribe(books => console.log(books));

        this.booksService.getArchivedBooks()
            .pipe(takeUntil(this.ngUnsubscribe))
            .subscribe(archivedBooks => console.log(archivedBooks));
    }

    ngOnDestroy() {
        this.ngUnsubscribe.next();
        this.ngUnsubscribe.complete();
    }
}
// app.component.html
<div *ngIf="products$ | async as products">
  <button *ngFor='let product of products'>
  	{{ product.name }}
  </button>
</div>

// app.component.ts
products$ = this.productService.products$;

// app.service.ts
products$ = this.http.get<Product[]>(this.url)
  .pipe(
  	tap(console.log),
  	catchError(this.handleError)
   );
star

Sun Jul 02 2023 19:03:51 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription/41177163#41177163

#javascript #angular #rxjs
star

Fri Dec 16 2022 16:19:38 GMT+0000 (Coordinated Universal Time) https://youtu.be/uv_sblwIJag?t=221

#angular #rxjs

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension