Ошибка при использовании интерфейса и наблюдаемый при разборе http - PullRequest
1 голос
/ 18 марта 2019

Структура файла в VS с ошибкой

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

Здесь все файлы находятся на одном уровне, и я передаю данные из employee.json компоненту employee с помощьюHTTP получить метод.но выдает ошибку

Ошибка
сообщение: «Ошибка Http во время синтаксического анализа для https://htpgeterror.stackblitz.io/employee.json" имя:« 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);
  }
}

URL-адрес Stackblitz https://stackblitz.com/edit/htpgeterror

1 Ответ

0 голосов
/ 18 марта 2019

Здесь вам необходимо сохранить файл employee.json в папке assets, чтобы служба Angular могла правильно обращаться к нему

Структура папки

app(folder)
  --> assets (folder)
        --> data (folder)
              --> employee.json // employee data file. 

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="assets/data/employee.json";
  constructor(private http:HttpClient) { }

  getEmp(): Observable<Employee[]>{
    return this.http.get<Employee[]>(this._url);
  }

}

Вот разветвленное решение на стеке

Надеюсь, это поможет!

...