In Angular 8 we can do like this:
import { Injectable } from '@angular/core';
import { YourModel} from '../models/<yourModel>.model';
import { UserService } from './user.service';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class GlobalDataService {
private me: <YourModel>;
private meObservable: Observable<User>;
constructor(private yourModalService: <yourModalService>, private http: HttpClient) {
}
ngOnInit() {
}
getYourModel(): Observable<YourModel> {
if (this.me) {
return of(this.me);
} else if (this.meObservable) {
return this.meObservable;
}
else {
this.meObservable = this.yourModalService.getCall<yourModel>() // Your http call
.pipe(
map(data => {
this.me = data;
return data;
})
);
return this.meObservable;
}
}
}
You can call it like this:
this.globalDataService.getYourModel().subscribe(yourModel => {
});
The above code will cache the result of remote API at first call so that it can be used on further requests to that method.