public getPosts(): Observable<Employee[]>{
this.http.get<Employee[]>('http://localhost:84/api/User').subscribe(data => {
console.log(data);
return data;
});
return;
}
从该函数出错无法读取未定义的属性"subscribe">
public getEmployees(){
this.appService.getPosts().subscribe(data => {
this.employees = data;
this.employees.shift();
});
}
您的服务不正确。您需要向调用者提供Observable数据。
public getPosts(): Observable<Employee[]>{
return this.http.get<Employee[]>('http://localhost:84/api/User');
}
您的服务中几乎没有问题。
- 您在
getPosts()
方法中返回undefined(最后一行中的return;
( - 您正在订阅
getPosts()
从而返回CCD_ 4而不是CCD_
如果您想在getPost
函数中进行控制台登录,您可以通过管道传输observable
并使用tap
运算符。
public getPosts(): Observable<Employee[]> {
return this.http.get<Employee[]>('http://localhost:84/api/User').pipe(
tap((data) => {
console.log(data);
})
);
}
您的getPosts
方法没有返回任何内容(undefined
(。
更改为:
return this.http.get<Employee[]>('http://localhost:84/api/User').subscribe(data => {
console.log(data);
return data;
});
(卸下return;
(
EDIT:您的代码还有另一个问题,它不会返回Observable
,而是返回Subscription
。
您应该进一步将其更改为:
return this.http.get<Employee[]>('http://localhost:84/api/User').pipe(
tap(data => console.log(data))
);
tap
是一种专门用于运行副作用并保持原始发射值的方法。