Created
September 28, 2017 22:23
-
-
Save rendfall/ff4043a54eb855c56bd557b07026bf71 to your computer and use it in GitHub Desktop.
Angular 2+ cache observable http result data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Injectable } from '@angular/core'; | |
| import { HttpClient } from '@angular/common/http'; | |
| import { Observable, ReplaySubject } from 'rxjs'; | |
| @Injectable() | |
| export class CachedService { | |
| data$: Observable<any> = this.dataSubject.asObservable(); | |
| private dataSubject = new ReplaySubject<any>(1); | |
| constructor(private http: HttpClient) {} | |
| fetch() { | |
| this.http.get('http://example.com') | |
| .subscribe(res => this.dataSubject.next(res)); | |
| } | |
| } | |
| // ... | |
| @Component({ | |
| selector: 'app-some-component', | |
| template: '', | |
| styles: '' | |
| }) | |
| export class SomeComponent implements OnInit { | |
| constructor(private service: CachedService) {} | |
| ngOnInit() { | |
| this.service.fetch(); | |
| this.service.data$.subscribe((data) => { | |
| // ... | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment