Skip to content

Instantly share code, notes, and snippets.

@rendfall
Created September 28, 2017 22:23
Show Gist options
  • Select an option

  • Save rendfall/ff4043a54eb855c56bd557b07026bf71 to your computer and use it in GitHub Desktop.

Select an option

Save rendfall/ff4043a54eb855c56bd557b07026bf71 to your computer and use it in GitHub Desktop.
Angular 2+ cache observable http result data
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