无法加载资源:尝试从json提取数据时,服务器响应状态为404(未找到)

时间:2018-12-26 11:59:09

标签: angular6

您好,尝试获取json数据时出现此错误

Service.ts文件显示错误,但正在编译

错误:

类型'Observable>'不能分配给类型'Observable'。   类型“ Promise”缺少类型“ IEmployee []”中的以下属性:length,pop,push,concat和26个以上。ts(2322)

员工是使用的界面

export interface IEmployee {
  id: number;
  firstName: string;
  lastName: string;
  salary: number;
  dob: string;
}

employees.service.ts

import { map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { IEmployee } from './iEmployee';
import {  Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable ()
export class EmployeeService {
  constructor(private http: HttpClient) {

  }
  getEmployees(): Observable<IEmployee[]> {
  return this.http.get('./employees.json')
   .pipe(map((res: Response) => res.json()));
  }
}

employees.component.ts

import { IEmployee } from './iEmployee';
import { Component, OnInit } from '@angular/core';
import { EmployeeService } from 'src/app/employees/employee.service';

@Component({
  selector: 'app-employees',
  templateUrl: './employees.component.html',
  styleUrls: ['./employees.component.css'] ,
  providers: [EmployeeService]
})
export class EmployeesComponent implements OnInit {

  employees: IEmployee[] = null;
    constructor(private empService: EmployeeService) {
      // this.employees = this.empService.getEmployees();
    }
  ngOnInit() {
    this.empService.getEmployees()
    .subscribe((empdata) => this.employees = empdata);
  }

}

即使我在app module.ts中包含了Http模块,并且在编译之后,仅表的标题是可见的,而数据则不可见

employees.component.html

<table style = "width: 50%">
  <thead>
    <tr>
      <th>Id</th>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Salary</th>
      <th>Date Of Birth</th>
    </tr>
  </thead>
  <tbody *ngIf="employees">
    <tr *ngFor = "let emp of employees">
      <td>{{emp.id}}</td>
      <td>{{emp.firstName | uppercase}}</td>
      <td>{{emp.lastName | lowercase}}</td>
      <td>{{emp.salary | currency:'INR': true}}</td>
      <td>{{emp.dob | date | uppercase}}</td>
    </tr>
    <tr *ngIf = "employees.length==0">
      <td colspan="5">No data to Display</td>
    </tr>
  </tbody>
  </table>

1 个答案:

答案 0 :(得分:0)

我将json文件移到了src文件夹中的资产文件夹中,并且我已将路径位置分配给'url'并将其用作

private_url ='/assets/data/employees.json';

将getEmployee方法用作

getEmployees():可观察的{

返回this.http.get(this.private_url);   }

现在正在显示值