首页 > 解决方案 > Observable 类型上不存在属性映射

问题描述

我试图从 Angular v4 更新到 Angular v6。我正在替换HttpandHttpModuleHttpClientand HttpClientModule。所以我HttpClient@angular/common/http服务中导入并试图从 DBpedia 的 API 中获取结果。我之前使用的是Httpfrom@angular/http并且我的以下代码工作正常

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Jsonp, Headers, RequestOptions, URLSearchParams} from "@angular/http";
import {Store} from "@ngrx/store";
import * as fromRoot from '../reducers';
import {Observable} from "rxjs";

@Injectable()
export class KnowledgeapiService {

  server = 'http://lookup.dbpedia.org';
  searchURL = this.server + '/api/search/KeywordSearch?';
  homepage = 'https://susper.com';
  logo = '../images/susper.svg';

  constructor(
    private http: HttpClient,
    private jsonp: Jsonp,
    private store: Store<fromRoot.State>
  ) {}

  public getsearchresults(searchquery){
    let params = new URLSearchParams();

    params.set('QueryString', searchquery);

    let headers = new Headers({ 'Accept': 'application/json' });
    let options:any = new RequestOptions({ headers: headers, search: params });

    return this.http
      .get(this.searchURL, options).map(res =>

        res.json()

      ).catch(this.handleError);
  }

  private handleError (error: any) {
    // In some advance version we can include a remote logging of errors
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // Right now we are logging to console itself
    return Observable.throw(errMsg);
  }
}

但是现在当我从Http依赖项迁移到时HttpClient,在函数中,getsearchresults(searchquery)每当我使用map函数映射数据到 json 时,它都会给出一个错误,即map函数在类型上不存在Observable<ArrayBuffer>。进一步删除map函数会为函数提供相同的消息catch。我点击了这个链接https://github.com/angular/angular/issues/15548但其中提供的解决方案对我不起作用。我错了?我应该删除两者mapcatchgetsearchresults(searchquery).

标签: angulartypescriptangular4-httpclientangular6

解决方案


基本上你面临的问题types。上面的打字稿代码不一致。例如,没有为getsearchresults()函数定义类型。没有定义类型this.http.get<NoTypeDefinedHere>

默认情况下进一步httpClient给出 json 响应let headers = new Headers({ 'Accept': 'application/json' });。这里可能不需要。

检查您是否在导入中使用http模块或模块。httpClient

检查是否rxjs/add/operator/map正确导入


推荐阅读