我正在构建一个angular 2服务来搜索特定信息。我的服务几乎可以正常使用,但是我不断收到此错误消息:

core.es5.js:1020 ERROR TypeError: res.json is not a function at MapSubscriber.project

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';


import { FundraiserProgressService } from 'app/services/fundraiser-progress.service';

@Injectable()
export class SearchService {
  baseUrl: String = 'http://localhost:4402/items';
  queryUrl: string = '?search=';

  constructor(private http: HttpClient) { }

  search(terms: Observable<string>) {
    return terms.debounceTime(400)
      .distinctUntilChanged()
      .switchMap(term => this.searchEntries(term));
  }

  searchEntries(term) {
    return this.http
      .get(this.baseUrl + this.queryUrl + term)
      .map((res: Response) => res.json())
  }
}

最佳答案

这是因为在Angular版本4.3.0中使用新的HttpClient时,JSON是假定的默认值,不再需要显式解析。因此,您可以删除.map((res: Response) => res.json())

这是取自documentation的示例:

@Component(...)
export class MyComponent implements OnInit {

  results: string[];

  // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    // Make the HTTP request:
    this.http.get('/api/items').subscribe(data => {
      // Read the result field from the JSON response.
      this.results = data['results'];
    });
  }
}

10-05 20:51
查看更多