Skip to content

Instantly share code, notes, and snippets.

@abiodun0
Created December 30, 2016 04:12
Show Gist options
  • Save abiodun0/6653811ed203e026356ee15fc229cfdf to your computer and use it in GitHub Desktop.
Save abiodun0/6653811ed203e026356ee15fc229cfdf to your computer and use it in GitHub Desktop.
avoid Angular 2 http method to fire an ajax everytime a component subscribes to it
export someClass {
private relplay: ReplaySubject<any> = new ReplaySubject<any>(1);
subscribeToReplay(): ReplaySubject<any> {
return this.replay;
}
callHttpRequest(someParams) {
this.http.post( ... ).subscribe(
(response) => {
// some actions
this.replay.next(response); // instead of response here may be other object or variables
}
);
}
....
export secondClass {
let subscription: Subscription = someClass.subscribeToReplay().subscribe(
(response) => {
// on response actions here
}
);
....
someClass.callHttpRequest({some params});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment