Angular 2路由器使用Observable解析

问题描述 投票:27回答:1

在发布Angular 2 RC.5之后,引入了路由器解析。 Here演示了Promise的例子,如果我用Observable向服务器发出请求,如何做同样的事情?

search.service.ts

...
searchFields(id: number) {
  return this.http.get(`http://url.to.api/${id}`).map(res => res.json());
}
...

搜索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);
  });
}

获取Object {fields: Subscriber}而不是真实数据。

angular angular2-routing rxjs5
1个回答
49
投票

不要在服务中调用subscribe(),而是让路由订阅。

更改

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

import 'rxjs/add/operator/first' // in imports

return this.searchService.searchFields().map(fields => {
  ...
}).first();

这样返回Observable而不是Subscription(由subscribe()返回)。

目前,路由器等待observable关闭。通过使用first()运算符,可以确保在第一个值发出后关闭它。

© www.soinside.com 2019 - 2024. All rights reserved.