gpt4 book ai didi

javascript - Angular 2搜索服务错误此: res. json不是函数

转载 作者:行者123 更新时间:2023-12-03 03:36:38 24 4
gpt4 key购买 nike

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

core.es5.js:1020 错误 TypeError: res.json 不是 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())
}
}

最佳答案

这是因为有了新的 HttpClient从 Angular 版本 4.3.0 开始,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'];
});
}
}

关于javascript - Angular 2搜索服务错误此: res. json不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45826057/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com