【问题标题】:how to make http get request in angular 2 http service with observables如何使用 observables 在 angular 2 http 服务中发出 http get 请求
【发布时间】:2017-10-09 03:42:44
【问题描述】:

我刚刚掌握了 Promise,现在我正在学习 Observables!呃!

只是尝试使用 Angular 4 发出一个简单的 get 请求。大致遵循本教程:https://scotch.io/tutorials/angular-2-http-requests-with-observables

最初,当我尝试从rxjs/Observable 导入Observable 时,我收到一个编译错误,基本上说map 不是Observable<Response> 的函数,但是将导入更改为仅rxjs 解决了编译错误。但是现在我在运行时遇到了同样的错误......

我处理以下回复的方式有什么问题?

import { Injectable } from '@angular/core';
import { apiConfig } from '../../environments/environment';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { APIRequest, APIResponse} from './api-objects';
import { Observable } from 'rxjs';

/**
 * The BaseAPIService can be extended to provide base functionality for communicating to the API endpoint.
 */
@Injectable()
export class BaseAPIService {

  private apiBase = apiConfig.base;

  constructor(protected http: Http) { }

  /**
   * Sends an API request to the endpoint
   */
  sendRequest(request: APIRequest): Observable<APIResponse> {
    const options = new RequestOptions({ });
    const fullUrl = `apiBase${request.url}`;
    request.body = request.body || {};
    return this.http.get(fullUrl).map((response: Response) => new APIResponse(response));
  }
}

** 错误详情**

this.http.get(...).map is not a function
    at CoreAPIService.webpackJsonp.356.BaseAPIService.sendRequest (base-api.service.ts:25)

【问题讨论】:

  • 您需要导入以下内容:import 'rxjs/add/operator/map';

标签: angular


【解决方案1】:

您还需要导入您计划使用的任何 RxJS 运算符。您可以在模块级别执行此操作。

例子:

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/switchMap';

【讨论】:

    猜你喜欢
    • 2017-09-09
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    相关资源
    最近更新 更多