Angular 5 HTTP加载JSON文件报错问题排查求助
问题排查与解决方案
嘿,这个错误很典型,我马上帮你搞定!
错误原因
你在newsService.ts里调用了res.json(),但Angular的HttpClient模块已经自动帮我们把JSON响应解析成JavaScript对象了——这是它和旧版Http模块的核心区别之一。当你拿到res的时候,它已经是解析好的数组/对象了,根本不存在json()方法,所以才会抛出TypeError: res.json is not a function。
修复后的代码
只需要修改NewsserviceService里的getNews方法,去掉多余的map(res => res.json())即可:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { INews } from './inews'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class NewsserviceService { public _url = 'http://localhost/admin/demo/api/get_posts/'; constructor( public http: HttpClient) { } getNews(): Observable<INews[]> { // 直接返回HttpClient的get结果,它已经自动解析了JSON return this.http.get<INews[]>(this._url); } }
额外提示
- 因为你指定了泛型
<INews[]>,请确保后端API返回的JSON结构和你的INews接口完全匹配,这样才能享受到Angular的类型安全特性。 - 如果你确实需要对响应数据做一些转换操作,可以保留
pipe(map(...)),但操作的是已经解析好的res对象,比如:return this.http.get<INews[]>(this._url).pipe( map(newsList => newsList.map(news => ({...news, content: news.content.trim()}))) );
内容的提问来源于stack exchange,提问作者user3172753
相关产品推荐
相关产品推荐

