Angular 2 router resolve with Observable

和自甴很熟 提交于 2019-11-27 03:59:29

问题


After release of Angular 2 RC.5 there was introduced router resolve. Here demonstrated example with Promise, how to do the same if I make request to 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.


回答1:


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.



来源:https://stackoverflow.com/questions/39066604/angular-2-router-resolve-with-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!