请帮助大家,当我尝试发出http请求时会发生此错误
这是我创建的服务:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
private _url: string = "/assets/data/employee.json";
constructor(private http : HttpClient) { }
getEmployee () {
return this.http.get(this._url);
}
}
这是我订阅服务的组件之一:
import { Component, OnInit, Input, EventEmitter, Output } from
'@angular/core';
import { EmployeeService } from '../employee.service';
@Component({
selector: '.app-test',
template: `
<h2>Employee List</h2>
<ul *ngFor="let employee of employeeList">
<li>{{employee.name}}</li>
</ul>
`,
styles: [`
`]
})
export class TestComponent implements OnInit {
public employeeList = [];
@Output() public childEvent = new EventEmitter();
constructor(private _employeeService : EmployeeService) { }
fireEvent() {
this.childEvent.emit('hey Omar');
}
ngOnInit() {
this.employeeList = this._employeeService.getEmployee();
}
}
这是来自vs代码的错误:
键入&#39; Observable&#39;不能分配给任何[]&#39;类型 财产包括&#39;类型&#39; Observable&#39;
中缺少
答案 0 :(得分:1)
http.get返回一个observable。
您需要获取其回调函数
中的数据this._employeeService.getEmployee()
.subscribe(data => {
this.employeeList = data;
});
此外,您可能希望初始化为任何内容以查看您获得的内容。你很可能得到一个对象,所以你可能想要从
开始employeeList: any;
如果是数组,那么您需要修改http请求以反映它
即。
this.http.get<employee_type>(this._url)