angularjs - share() vs ReplaySubject: Which one, and neither works -
i'm trying implement short-term caching in angular service -- bunch of sub-components created in rapid succession, , each 1 has http call. want cache them while page loading, not forever.
i've tried following 2 methods, neither of have worked. in both cases, http url hit once each instance of component created; want avoid -- ideally, url hit once when grid created, cache expires , next time need create component hits url on again. pulled both techniques other threads on stackoverflow.
share() (in service)
getdata(id: number): observable<myclass[]> { return this._http.get(this.url) .map((response: response) => <myclass[]>response.json()) .share(); } replaysubject (in service)
private replaysubject = new replaysubject(1, 10000); getdata(id: number): observable<myclass[]> { if (this.replaysubject.observers.length) { return this.replaysubject; } else { return this._http.get(this.url) .map((response: response) => { let data = <myclass[]>response.json(); this.replaysubject.next(data); return data; }); } } caller (in component)
ngoninit() { this.myservice.getdata(this.id) .subscribe((resultdata: myclass[]) => { this.data = resultdata; }, (error: any) => { alert(error); }); } there's no need hit url each time component created -- return same data, , in grid of rows contain component, data same. could call once when grid created, , pass data component. want avoid that, 2 reasons: first, component should relatively self-sufficient. if use component elsewhere, don't want parent component have cache data there, too. second, want find short-term caching pattern can applied elsewhere in application. i'm not person working on this, , want keep code clean.
most importantly, if want make persistent when creating/destroying angular components can't created in component in service shared among components.
regarding rxjs, don't have use replaysubject directly , use publishreplay(1, 10000)->refcount() instead.
the share() operator shorthand publish()->refcount() uses subject internally means doesn't replay cached values.
for detailed explanation how use publishreplay()->refcount() make cache have @ example in documentation detailed explanation how , why works: caching http responses
Comments
Post a Comment