调用 http 函数时没有触发 XHR 请求

No XHR request is fired when calling http function

我正在努力在 angular2 中设置一个应该与 REST 后端通信的服务。

我正在尝试设置一个最小示例,该示例应将请求发送到休息后端并处理响应。服务被正确调用,我的控制台显示消息

'calling the star wars api';

问题是我检查了浏览器开发工具网络部分中的 xhr 选项卡,没有触发任何 xhr 请求。 似乎函数 extractData 和 handleError 似乎也没有被调用,尽管我在 map 和 catch 中定义了它们。

我是不是漏掉了什么?为什么我调用这个服务没有发送xhr请求?

这是我的服务:

import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { Token } from './token';

@Injectable()
export class UserService {
  constructor(private http: Http) {
  }

  getAll() : Observable<Token[]>{
    console.log('calling the star wars api');
    let people$ = this.http
      .get('http://swapi.co/api/people', {headers: this.getHeaders()})
      .map(this.extractData)
      .catch(this.handleError);
    return people$;
  }
  private getHeaders(){
    let headers = new Headers();
    headers.append('Accept', 'application/json');
    return headers;
  }


  private extractData(res: Response) {
    console.log('data extracted!');
    let body = res.json();
    return body.data || { };
  }
  private handleError (error: Response | any) {
    // In a real world app, we might use a remote logging infrastructure
    console.log('an error ocurred');
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

}

我使用 angular-cli 设置项目、组件和服务。我正在使用 angular2 版本 2.4.0

感谢 0x2D9A3 的评论,我得以解决问题。

问题是我从我的组件调用 UserService 的方式。

this.userService.getAll()

只是调用了服务,但没有触发任何 XHR 请求。
然而,

this.userService.getAll().subscribe((result) => {
      if (result) {
        console.log('successfull xhr request');
      }
}

确实成功调用了 xhr 请求,因为这是必须使用 Observable 的方式。

这是来自 angular docs

Think of an Observable as a stream of events published by some source. To listen for events in this stream, subscribe to the Observable. These subscriptions specify the actions to take when the web request produces a success event (with the data in the event payload) or a fail event (with the error in the payload).