Angular 无法通过可观察的服务调用方法
Angular cannot call method from service with observable
我有一个使用此代码的服务:
cars() {
return 'something here';
}
然后我想从组件中获取带有可观察对象的数据,所以我这样做了:
getcars() {
this.dataService.cars().subscribe((result) => {
console.log(result);
});
}
我不能这样做,因为我得到:
Error: Property 'subscribe' does not exist on type 'string'.
我该如何解决这个问题?
错误消息:属性 'subscribe' 在类型 'string' 上不存在。告诉您您正在尝试对字符串调用 subscribe()
函数。字符串不是您可以订阅的 Observable。您不应该使用订阅或 return 从服务中观察到的。
要从值创建可观察对象,您可以使用 of
。
import { of } from 'rxjs';
cars() {
return of('something here');
}
我有一个使用此代码的服务:
cars() {
return 'something here';
}
然后我想从组件中获取带有可观察对象的数据,所以我这样做了:
getcars() {
this.dataService.cars().subscribe((result) => {
console.log(result);
});
}
我不能这样做,因为我得到:
Error: Property 'subscribe' does not exist on type 'string'.
我该如何解决这个问题?
错误消息:属性 'subscribe' 在类型 'string' 上不存在。告诉您您正在尝试对字符串调用 subscribe()
函数。字符串不是您可以订阅的 Observable。您不应该使用订阅或 return 从服务中观察到的。
要从值创建可观察对象,您可以使用 of
。
import { of } from 'rxjs';
cars() {
return of('something here');
}