使用接口时出错,并且http解析时可观察到

湿婆钱德尔

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

在这里,所有文件都处于同一级别,我正在使用HTTP get方法将数据从employee.json传递到员工组件。但是它产生了错误

错误
消息:“在解析https://htpgeterror.stackblitz.io/employee.json时出现Http错误”名称:“ HttpErrorResponse”,错误:对象

employee.json

[
  {"id":2,"name":"Shiva","age":23},
  {"id":3,"name":"ABC","age":25},
]

员工

export interface Employee {
  id:number,
  name:string,
  age:number,
}

员工服务

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

员工列表.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);
  }
}

Stackblitz网址https://stackblitz.com/edit/htpgeterror

帕拉姆

在这里,您需要将employee.json文件保存在文件assets下,以便角度服务可以正确访问它

资料夹结构

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

服务

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

}

这是Stackblitz上的分叉解决方案

希望这会有所帮助!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

更新可观察到的“ roles [0]未定义”时出错

HTTP可观察到的响应解析为数组

使用可观察到的无法解析的方法用handleResponse

任一可观察到的更新时触发代码

角度-单击时清除可观察到的

打印单击按钮时可观察到的结果?

角度:使用管道和选项卡时,可观察到的更改行为

使用HttpClient时,如何从可观察到的响应中提取令牌?

使用GDB时观察到的问题

Angular HTTP可观察到的元组

可观察到可观察的顺序

可观察到的角度解析器过早完成

每次在Angular 2中满足条件时,rxJS即可观察到重复调用

等待可观察到的RxJS时在Angular中显示加载指示器

当基础数据源具有新值时,了解可观察到的RxJava

RxJs和redux可观察到。Ajax成功或失败时附加值

我需要像CombineLatest这样的东西,但是当任何可观察到的东西发出时

将“订阅时”回调附加到可观察到的

映射可观察到可完成时不调用RxJava2订阅

可观察到的提交时没有刷新吗?Knockoutjs(提供提琴)

绑定为可观察到的敲除时如何更新ckeditor数据?

当另一个发出值时,可观察到RxJS错误

可观察到的更新时,所选选项不会更新,尽管optionsValue确实会更新

当数组开始为空时,可观察到的数组mobx不会更新

转发时发出进度项可观察到一个

重新初始化对象擦除事件时可观察到的FromEventPattern

当可观察到的条件满足时,RxJS停止foreach

可观察到的异步

刷新可观察到