Angular 2 router resolve con Observable
Después del lanzamiento de Angular 2 RC.5 se introdujo router resolve. Aquí ejemplo demostrado con Promesa, cómo hacer lo mismo si hago solicitud al servidor con Observable?
Buscar.Servicio.ts
...
searchFields(id: number) {
return this.http.get(`http://url.to.api/${id}`).map(res => res.json());
}
...
Resolución de búsqueda.Servicio.ts
import { Injectable } from '@angular/core';
import { Router, Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { SearchService } from '../shared';
@Injectable()
export class SearchResolveService implements Resolve<any> {
constructor(
private searchService: SearchService ,
private router: Router
) {}
resolve(route: ActivatedRouteSnapshot): Observable<any> | Promise<any> | any {
let id = +route.params['id'];
return this.searchService.searchFields(id).subscribe(fields => {
console.log('fields', fields);
if (fields) {
return fields;
} else { // id not found
this.router.navigate(['/']);
return false;
}
});
}
}
Buscar.componente.ts
ngOnInit() {
this.route.data.forEach((data) => {
console.log('data', data);
});
}
Obtener Object {fields: Subscriber}
en lugar de datos reales.
25
Author: Rakhat Jabagin, 2016-08-21
1 answers
No llame a subscribe()
en su servicio y deje que la ruta se suscriba.
Cambiar
return this.searchService.searchFields().subscribe(fields => {
A
import 'rxjs/add/operator/first' // in imports
return this.searchService.searchFields().map(fields => {
...
}).first();
De esta manera se devuelve un Observable
en lugar de un Subscription
(que es devuelto por subscribe()
).
Actualmente el router espera a que se cierre el observable. Puede asegurarse de que se cierra después de que se emite el primer valor, utilizando el operador first()
.
46
Author: Günter Zöchbauer,
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-03-06 21:12:43
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-03-06 21:12:43