public getPosts(): Observable<Employee[]>{
this.http.get<Employee[]>('http://localhost:84/api/User').subscribe(data => {
console.log(data);
return data;
});
return;
}
通过这个函数出错 无法读取未定义的属性“订阅”
public getEmployees(){
this.appService.getPosts().subscribe(data => {
this.employees = data;
this.employees.shift();
});
}
答案 0 :(得分:2)
您的服务不正确。您需要向调用方提供 Observable 数据。
public getPosts(): Observable<Employee[]>{
return this.http.get<Employee[]>('http://localhost:84/api/User');
}
答案 1 :(得分:2)
您的服务几乎没有问题。
getPosts()
方法中返回 undefined(最后一行为 return;
)。getPosts()
因此返回 Subscription
而不是 Observable
如果您想控制台登录您的 getPost
函数,您可以使用管道 observable
并使用 tap
运算符来达到您的目的。
public getPosts(): Observable<Employee[]> {
return this.http.get<Employee[]>('http://localhost:84/api/User').pipe(
tap((data) => {
console.log(data);
})
);
}
答案 2 :(得分:0)
您的 undefined
方法没有返回任何内容 (getPosts
)。
改为:
return this.http.get<Employee[]>('http://localhost:84/api/User').subscribe(data => {
console.log(data);
return data;
});
(去掉 return;
)
编辑:您的代码还有另一个问题,它不会返回 Observable
而是返回 Subscription
。
您还应该将其更改为:
return this.http.get<Employee[]>('http://localhost:84/api/User').pipe(
tap(data => console.log(data))
);
tap
是一种专用于运行副作用并保持原始值发出的方法。