html - 在 Angular 中使用 HTTP 获取数据
问题描述
我是 Angular 和 Http 服务的新手。我创建了一个员工列表组合和一个名为employee.service.ts 的服务,它进行Http 调用。我也正确地映射了可观察对象,
我还在资产中创建了一个名为 employee.json 的 json 文件,其中存储了我的数据。没有任何编译错误。但它在运行时失败。我收到以下错误。
NullInjectorError: R3InjectorError(AppModule)[EmployeeService -> EmployeeService -> EmployeeService]:
员工列表.component.html
<h2>Employee List</h2>
<ul *ngFor="let employee of employees">
<li>{{employee.name}}</li>
</ul>
员工服务.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { IEmployee } from '../employee';
import { Observable } from 'rxjs';
@Injectable() export class EmployeeService{
private _url: string ="/assets/data/employee.json";
constructor(private http:HttpClient) {}
getEmployees(): Observable<IEmployee[]>{
return this.http.get<IEmployee[]>(this._url);
}
}
员工列表.component.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { IEmployee } from '../employee';
import { Observable } from 'rxjs';
@Injectable() export class EmployeeService{
private _url: string ="/assets/data/employee.json";
constructor(private http:HttpClient) {}
getEmployees(): Observable<IEmployee[]>{
return this.http.get<IEmployee[]>(this._url);
}
}
解决方案
错误很清楚。您应该必须在 module.ts 中提供employeeService
import employeeService
并将“EmployeeService”添加到提供者数组
推荐阅读
- javascript - 按属性对具有键和子对象的对象进行排序
- mongodb - 演员的 mognodb 聚合组
- javascript - 动态依赖下拉 laravel
- python - 如何在python的嵌套字典中追加数据
- python - 查找异常值的函数
- javascript - 如何更改密码元素输入 JavaScript 的文本
- mongodb - 在 express (async/await) 中使用一个 mongoose 查询的输出作为另一个查询的输入
- r - 使用 data.table 进行非等连接时重命名连接变量
- javascript - 在 React.js 上验证电话号码
- html - CSS:如何按类设置内容?