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组件。但它产生了错误
错误 消息:“解析https://htpgeterror.stackblitz.io/employee.json期间的Http失败”名称:“HttpErrorResponse”,错误:对象
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);
}
}
员工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 url https://stackblitz.com/edit/htpgeterror
在这里你需要保持employee.json
文件夹下的assets
文件,以便角度服务可以正确访问它
文件夹结构
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
希望这会有所帮助!