Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 router resolve with Observable

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.

like image 471
Rakhat Avatar asked Aug 21 '16 16:08

Rakhat


People also ask

What is resolvers in Angular?

So what is Angular Resolver? Angular Route Resolver is used for pre-fetching some of the data when the user is navigating from one route to another. It can be defined as a smooth approach for enhancing user experience by loading data before the user navigates to a particular component.

What is Routerstatesnapshot in Angular?

This is a tree of activated route snapshots. Every node in this tree knows about the "consumed" URL segments, the extracted parameters, and the resolved data. The following example shows how a component is initialized with information from the snapshot of the root node's state at the time of creation.

What is the use of AuthGuard in Angular?

AuthGuard is used to protect the routes from unauthorized access in angular.

What is CanActivate in Angular?

CanActivatelinkInterface that a class can implement to be a guard deciding if a route can be activated. If all guards return true , navigation continues. If any guard returns false , navigation is cancelled.


1 Answers

Don't call subscribe() in your service and instead let the route subscribe.

Change

return this.searchService.searchFields().subscribe(fields => { 

to

import 'rxjs/add/operator/first' // in imports  return this.searchService.searchFields().map(fields => {   ... }).first(); 

This way an Observable is returned instead of a Subscription (which is returned by subscribe()).

Currently the router waits for the observable to close. You can ensure it gets closed after the first value is emitted, by using the first() operator.

like image 197
Günter Zöchbauer Avatar answered Sep 23 '22 03:09

Günter Zöchbauer