File Structure in VS with error
app(folder)
-->employee-list(folder)
-->employee-list.component.html
-->employee-list.component.ts
-->app.component.html
-->app.component.ts
-->app.module.ts
-->employee.json
-->employee.service.ts
-->employee.ts
在这里,所有文件都在同一层,我使用 HTTP get 方法将数据从 employee.json 传递到 employee 组件。但它产生了错误
Error
message: "Http failure during parsing for https://htpgeterror.stackblitz.io/employee.json" name: "HttpErrorResponse", error:Object
employee.json
[
{"id":2,"name":"Shiva","age":23},
{"id":3,"name":"ABC","age":25},
]
employee.ts
export interface Employee {
id:number,
name:string,
age:number,
}
employee.service.ts
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Employee} from './employee';
import {Observable} from 'rxjs';
@Injectable()
export class EmployeeService {
public _url:string="./employee.json";
constructor(private http:HttpClient) { }
getEmp(): Observable<Employee[]>{
return this.http.get<Employee[]>(this._url);
}
}
employee-list.component.ts
import { Component, OnInit } from '@angular/core';
import {EmployeeService} from '../employee.service';
@Component({
selector: 'app-employee-list',
templateUrl: './employee-list.component.html',
styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {
public employee=[];
constructor(private _employeeService:EmployeeService) { }
ngOnInit() {
this._employeeService.getEmp()
.subscribe(data => this.employee = data);
}
}
Stackblitz 网址 https://stackblitz.com/edit/htpgeterror
最佳答案
这里你需要把你的employee.json
文件放在assets
文件夹下,这样angular服务才能正常访问它
文件夹结构
app(folder)
--> assets (folder)
--> data (folder)
--> employee.json // employee data file.
service.ts
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Employee} from './employee';
import {Observable} from 'rxjs';
@Injectable()
export class EmployeeService {
public _url:string="assets/data/employee.json";
constructor(private http:HttpClient) { }
getEmp(): Observable<Employee[]>{
return this.http.get<Employee[]>(this._url);
}
}
Here is forked solution on stackblitz
希望这会有所帮助!
关于angular - 在 http 解析中使用接口(interface)和 Observable 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55224404/