在Angular中使用HTTP获取数据



我是Angular和Http服务的新手。我创建了一个员工列表comp和一个名为employee.service.ts的服务,该服务进行Http调用。我还正确地绘制了可观测的

我还在资产中创建了一个名为employee.json的json文件,用于存储我的数据。没有任何编译错误。但它在运行时失败。我收到以下错误。

NullInjectorError: R3InjectorError(AppModule)[EmployeeService -> EmployeeService -> EmployeeService]:

employee-list.component.html

<h2>Employee List</h2>
<ul *ngFor="let employee of employees">
<li>{{employee.name}}</li>
</ul>

employee.service.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);
}
}

employee-list.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);
}
}

错误非常明显。你应该在模块.ts 中提供employeeService

import employeeService 

并将"EmployeeService"添加到提供商阵列

相关内容

  • 没有找到相关文章

最新更新