|
| 1 | +import {Component, OnInit} from '@angular/core'; |
| 2 | +import {Observable, of} from 'rxjs'; |
| 3 | +import {pluck, shareReplay, switchMap, catchError, tap, filter, map} from 'rxjs/operators'; |
| 4 | +import {Post} from '../posts/posts.component'; |
| 5 | +import {isScullyGenerated, TransferStateService} from '@scullyio/ng-lib'; |
| 6 | +import {ActivatedRoute} from '@angular/router'; |
| 7 | +import {HttpClient} from '@angular/common/http'; |
| 8 | + |
| 9 | +@Component({ |
| 10 | + selector: 'app-post', |
| 11 | + templateUrl: './post.component.html', |
| 12 | + styleUrls: ['./post.component.css'], |
| 13 | +}) |
| 14 | +export class PostComponent implements OnInit { |
| 15 | + postId$: Observable<number> = this.route.params.pipe( |
| 16 | + pluck('post'), |
| 17 | + filter(val => ![undefined, null].includes(val)), |
| 18 | + map(val => parseInt(val, 10)), |
| 19 | + shareReplay(1) |
| 20 | + ); |
| 21 | + |
| 22 | + apiPosts$ = this.postId$.pipe( |
| 23 | + switchMap(id => |
| 24 | + this.http.get<Post>(`https://jsonplaceholder.typicode.com/posts/${id}`).pipe( |
| 25 | + catchError(() => |
| 26 | + of({ |
| 27 | + id, |
| 28 | + title: 'not found', |
| 29 | + } as Post) |
| 30 | + ) |
| 31 | + ) |
| 32 | + ), |
| 33 | + shareReplay(1) |
| 34 | + ); |
| 35 | + |
| 36 | + // This is an example of using TransferState |
| 37 | + post$ = isScullyGenerated() |
| 38 | + ? this.transferState.getState<Post>('post') |
| 39 | + : this.apiPosts$.pipe(tap(post => this.transferState.setState('post', post))); |
| 40 | + |
| 41 | + constructor( |
| 42 | + private route: ActivatedRoute, |
| 43 | + private http: HttpClient, |
| 44 | + private transferState: TransferStateService |
| 45 | + ) { |
| 46 | + console.log('post inits'); |
| 47 | + } |
| 48 | + |
| 49 | + ngOnInit() {} |
| 50 | +} |
0 commit comments