Skip to content

Instantly share code, notes, and snippets.

@parthghiya
Created September 22, 2017 16:54
Show Gist options
  • Save parthghiya/aef426437b9082c6aad4c5c424c3df14 to your computer and use it in GitHub Desktop.
Save parthghiya/aef426437b9082c6aad4c5c424c3df14 to your computer and use it in GitHub Desktop.
Caching Service Data Using Replayable Subject (RxJS) In Angular
import { TestService } from './../services/test.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-comp1',
templateUrl: './comp1.component.html',
styleUrls: ['./comp1.component.css']
})
export class Comp1Component implements OnInit {
constructor(private testService:TestService) { }
user:any;
ngOnInit() {
}
/*This function is used whenever we want to make a fresh server call*/
getFreshData(){
this.testService.getData();
this.subscriptionFunction();
}
/*This Method is used whenever we want to get Data From Cache*/
getCachedData(){
this.subscriptionFunction();
}
/*Common function in both which basically subscribes an observable*/
subscriptionFunction(){
this.testService.data$.subscribe(res=>{
this.user=res.json();
},err=>{
console.log("error");
});
}
}
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Http, Response } from '@angular/http';
import {ReplaySubject } from 'rxjs';
@Injectable()
export class TestService {
dataSubject=new ReplaySubject<Response>(null as any ); //this is where we store the cache data
data$: Observable<Response> = this.dataSubject.asObservable(); //this is we return as observable
constructor(private http:Http) { }
/*Data which we get we store it in our subject, if we want fresh call we update our subject, else we just return the cached subject.*/
getData(){
this.http.get('https://jsonplaceholder.typicode.com/posts').
subscribe(res=>this.dataSubject.next(res));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment