【发布时间】:2019-03-18 15:07:23
【问题描述】:
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 传递到员工组件。但它正在产生错误
错误
消息:“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);
}
}
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
【问题讨论】:
-
ng serve(假设您正在使用)不在根目录提供 JSON 文件。他们需要在资产之下。 -
请您分享一下stackblitz,以便修复错误
-
我已经在 stackblitz 上分叉并提供了解决方案。请检查
标签: angular typescript http service mean-stack