【问题标题】:Fetch data using HTTP in Angular在 Angular 中使用 HTTP 获取数据
【发布时间】:2020-04-27 13:42:27
【问题描述】:

我是 Angular 和 Http 服务的新手。我创建了一个员工列表组合和一个名为employee.service.ts 的服务,它进行Http 调用。我也正确地映射了 observable,

我还在资产中创建了一个名为 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>

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);
    }
}

【问题讨论】:

  • 我认为你有两个同名的课程EmployeeService
  • @Azad 不,只有一个名为“EmployeeService”的类

标签: html angular typescript web-services


【解决方案1】:

错误很明显。您应该必须在 module.ts 中提供employeeService

import employeeService 

并将“EmployeeService”添加到提供者数组中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 2020-08-07
    • 2016-11-08
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多