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传递到员工组件。但是它产生了错误
错误
消息:“在解析https://htpgeterror.stackblitz.io/employee.json时出现Http错误”名称:“ HttpErrorResponse”,错误:对象
employee.json
[
{"id":2,"name":"Shiva","age":23},
{"id":3,"name":"ABC","age":25},
]
员工
export interface Employee {
id:number,
name:string,
age:number,
}
员工服务
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);
}
}
员工列表.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
夹下,以便角度服务可以正确访问它
资料夹结构
app(folder)
--> assets (folder)
--> data (folder)
--> employee.json // employee data file.
服务
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);
}
}
希望这会有所帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句