After the release of Angular 2 RC.5 there was introduced router resolve. Here demonstrated example with Promise, how to do the same if I make a request to the server with Observable?
search.service.ts
searchFields(id: number) {
return this.http.get(`http://url.to.api/${id}`).map(res => res.json());
}
search-resolve.service.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;
}
});
}
}
search.component.ts
ngOnInit() {
this.route.data.forEach((data) => {
console.log('data', data);
});
}
Get Object {fields: Subscriber}
instead of real data.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…