Angular 5中使用HttpClient无法读取本地JSON数据求助
解决Angular 5中HttpClient读取本地JSON数据失败的问题
我帮你排查下问题,主要有两个关键错误导致你无法读取本地JSON:
1. 服务中的JSON文件路径错误
你在employee.service.ts里写的路径是"src/app/api/employee.json",但这个是源码目录的路径——Angular构建项目后,assets配置里的文件会被复制到dist目录的根路径下(对应项目运行时的根路径),源码目录结构不会被保留,所以你得用运行时的相对路径:
修改employee.service.ts中的url:
import {Injectable} from "@angular/core"; import {HttpClient} from "@angular/common/http"; import "rxjs/add/operator/map"; @Injectable() export class EmployeeService { // 改为运行时的相对路径,对应assets构建后的位置 url: string = "./api/employee.json" constructor(private http: HttpClient) {} getEmployee() { return this.http.get(this.url) } }
2. 组件中的变量赋值逻辑错误
在employee.component.ts里,你把subscribe回调的参数list和组件自身的this.list搞混了,导致数据没有正确赋值:
修改组件代码:
import {Component} from "@angular/core" import {EmployeeService} from './employee.service' @Component({ selector:'app-employee', templateUrl:'./employee.component.html' }) export class EmployeeComponent { list:any; data:any; constructor(private employee:EmployeeService){} ngOnInit() { this.employee.getEmployee().subscribe(list=>{ // 用回调参数list,而非未赋值的this.list this.data = list.data; // 打印正确的返回数据 console.log(this.data); }) } }
额外确认:angular-cli.json的assets配置
你的angular-cli.json里已经把src/app/api/employee.json加入了assets数组,这个配置是正确的——构建时它会自动把该JSON文件复制到dist/demo/api/employee.json,所以上面的相对路径能正常访问到。
完成以上修改后,重启项目(ng serve),应该就能正常读取本地JSON数据了。
内容的提问来源于stack exchange,提问作者Vinay Anand
相关产品推荐
相关产品推荐

