resultados de almacenamiento en caché con el servicio http angular2 [duplicar]
Esta pregunta ya tiene una respuesta aquí:
- ¿Cuál es la forma correcta de compartir el resultado de una llamada a red Http Angular en RxJS 5? 19 respuestas
Expongo una solicitud HTTP GET a través de un servicio, y varios componentes están utilizando estos datos (detalles del perfil de un usuario). Me gustaría que la primera solicitud de componente realmente realice el HTTP GET solicite al servidor y almacene en caché los resultados para que las solicitudes consecuentes utilicen los datos almacenados en caché, en lugar de volver a llamar al servidor.
Aquí hay un ejemplo para el servicio, cómo recomendaría implementar esta capa de caché con Angular2 y typescript.
import {Inject, Injectable} from 'angular2/core';
import {Http, Headers} from "angular2/http";
import {JsonHeaders} from "./BaseHeaders";
import {ProfileDetails} from "../models/profileDetails";
@Injectable()
export class ProfileService{
myProfileDetails: ProfileDetails = null;
constructor(private http:Http) {
}
getUserProfile(userId:number) {
return this.http.get('/users/' + userId + '/profile/', {
headers: headers
})
.map(response => {
if(response.status==400) {
return "FAILURE";
} else if(response.status == 200) {
this.myProfileDetails = new ProfileDetails(response.json());
return this.myProfileDetails;
}
});
}
}
3 answers
Con respecto a su último comentario, esta es la forma más fácil que se me ocurre : Crear un servicio que tendrá una propiedad y esa propiedad mantendrá la solicitud.
class Service {
_data;
get data() {
return this._data;
}
set data(value) {
this._data = value;
}
}
Tan simple como eso. Todo lo demás en el plnkr estaría intacto. Eliminé la solicitud del Servicio porque se instanciará automáticamente (no hacemos new Service...
, y no soy consciente de una forma fácil de pasar un parámetro a través del constructor).
Así que, ahora, tenemos el Servicio, lo que hacemos ahora es hacer la solicitud en nuestro componente y asignarlo a la variable de servicio data
class App {
constructor(http: Http, svc: Service) {
// Some dynamic id
let someDynamicId = 2;
// Use the dynamic id in the request
svc.data = http.get('http://someUrl/someId/'+someDynamicId).share();
// Subscribe to the result
svc.data.subscribe((result) => {
/* Do something with the result */
});
}
}
Recuerde que nuestra instancia de servicio es la misma para cada componente, por lo que cuando asignamos un valor a data
se reflejará en cada componente.
Aquí está el plnkr con un ejemplo de trabajo.
Referencia
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-12 20:12:03
El operador share() funciona solo en la primera solicitud, cuando se sirven todas las suscripciones y se crea otra, entonces no funcionará, hará otra Solicitud. (este caso es bastante común, en cuanto al SPA angular2 siempre crea/destruye componentes)
Usé un ReplaySubjectpara almacenar el valor del http observable. El ReplaySubject observable puede servir un valor anterior a sus suscriptores.
el Servicio:
@Injectable()
export class DataService {
private dataObs$ = new ReplaySubject(1);
constructor(private http: HttpClient) { }
getData(forceRefresh?: boolean) {
// If the Subject was NOT subscribed before OR if forceRefresh is requested
if (!this.dataObs$.observers.length || forceRefresh) {
this.http.get('http://jsonplaceholder.typicode.com/posts/2').subscribe(
data => this.dataObs$.next(data),
error => {
this.dataObs$.error(error);
// Recreate the Observable as after Error we cannot emit data anymore
this.dataObs$ = new ReplaySubject(1);
}
);
}
return this.dataObs$;
}
}
El Componente:
@Component({
selector: 'my-app',
template: `<div (click)="getData()">getData from AppComponent</div>`
})
export class AppComponent {
constructor(private dataService: DataService) {}
getData() {
this.dataService.getData().subscribe(
requestData => {
console.log('ChildComponent', requestData);
},
// handle the error, otherwise will break the Observable
error => console.log(error)
);
}
}
}
ÉMBOLO completamente funcional
(observe la consola y la pestaña de red)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-25 15:49:54
He omitido el userId
manejo. Requeriría administrar un array de data
y un array de observable
(uno para cada userId
solicitado) en su lugar.
import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/observable/of';
import 'rxjs/add/operator/share';
import 'rxjs/add/operator/map';
import {Data} from './data';
@Injectable()
export class DataService {
private url:string = 'https://cors-test.appspot.com/test';
private data: Data;
private observable: Observable<any>;
constructor(private http:Http) {}
getData() {
if(this.data) {
// if `data` is available just return it as `Observable`
return Observable.of(this.data);
} else if(this.observable) {
// if `this.observable` is set then the request is in progress
// return the `Observable` for the ongoing request
return this.observable;
} else {
// example header (not necessary)
let headers = new Headers();
headers.append('Content-Type', 'application/json');
// create the request, store the `Observable` for subsequent subscribers
this.observable = this.http.get(this.url, {
headers: headers
})
.map(response => {
// when the cached data is available we don't need the `Observable` reference anymore
this.observable = null;
if(response.status == 400) {
return "FAILURE";
} else if(response.status == 200) {
this.data = new Data(response.json());
return this.data;
}
// make it shared so more than one subscriber can get the result
})
.share();
return this.observable;
}
}
}
Ejemplo de émbolo
Puede encontrar otra solución interesante en https://stackoverflow.com/a/36296015/217408
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:37