import {Component, OnDestroy, OnInit} from '@angular/core'; import {Region} from '../../interfaces/region.interface'; import {BookmarkService} from '../../services/bookmark.service'; import {DataService} from '../../services/data.service'; import {catchError, switchMap, takeUntil, tap} from 'rxjs/operators'; import {Router} from '@angular/router'; import {Subject} from 'rxjs'; import {HttpErrorResponse} from '@angular/common/http'; @Component({ selector: 'app-bookmark-list', templateUrl: './bookmark-list.component.html', styleUrls: ['./bookmark-list.component.scss'] }) export class BookmarkListComponent implements OnInit, OnDestroy { bookmarks: Region[]; isLoading = true; message: string; private destroyed$ = new Subject(); constructor(private bs: BookmarkService, private ds: DataService, private router: Router) { } ngOnInit() { this.bs.getRegionIds().pipe( takeUntil(this.destroyed$), tap(() => this.isLoading = true), switchMap(ids => { const regions: Promise[] = ids.map(id => this.ds.getRegion(id)); return Promise.all(regions); }), catchError((err, caught) => { this.message = `${(err as HttpErrorResponse).status}: ${(err as HttpErrorResponse).statusText} :/`; return caught; }) ).subscribe(regions => { this.bookmarks = regions; this.message = undefined; this.isLoading = false; }); } onBookmarkClick(region: Region) { this.router.navigate(['/region', region.region_id]).catch(console.log); } ngOnDestroy(): void { this.destroyed$.next(); this.destroyed$.complete(); } }