angular - Type 'void' is not assignable to type 'Observable' How can I fix this?
问题描述
I'm trying to pass the return value of my API to my BehaviorSubject, but I'm encountering the Typescript error above. It's not clear to me how to fix it. The line of code that is causing the error is return this.sleepReponse.next(score)
How should this be passed to my BehaviorSubject?
export class SleepService {
private endpoint = '';
private sleepResponse = new BehaviorSubject<any>({});
currentResponse = this.sleepResponse.asObservable();
constructor(private http: HttpClient) { }
public postSleepDuration(score: string, forceResponse?: boolean, errorCode?: number): Observable<any | HttpErrorResponse> {
if (forceResponse === undefined) {
return this.http.post<any>(this.endpoint, score );
} else {
const accounts = RESULTS_MOCK;
const error = mockError(errorCode, this.endpoint);
console.log('forceREsponse', of(accounts))
let response = !!forceResponse ? of(accounts) : throwError(error);
return this.sleepResponse.next(response)
}
}
}
const RESULTS_MOCK: any = {
count: 1,
next: null,
previous: null,
status: 200,
results: [
{
id: "1",
name: "Asleep and In bed results"
}
]
}
解决方案
使用管道有效。
public postSleepDuration(score: string, forceResponse?: boolean, errorCode?: number): Observable<any | HttpErrorResponse> {
if (forceResponse === undefined) {
return this.http.post<any>(this.endpoint, score );
} else {
const accounts = RESULTS_MOCK;
const mockedError = mockError(errorCode);
return of(accounts).pipe(
tap(response => {
this.sleepResponse.next(response)
}),
catchError(error =>
throwError(mockedError) )
)
}
}
推荐阅读
- keycloak - PWA 中的 keycloak-js 客户端不使用存储中的缓存令牌
- powershell - 即使我输入的 CMDpath 是正确的,为什么在 PowerShell 中会出现此错误?
- flutter - 当删除需要回来查看更改时,小部件中的颤振项目未更新
- scala - 在加特林进纸器中加载更多文件
- css - 更改下拉菜单的背景颜色会使 Bootstrap 中的选定项目完全变白
- c# - OPC/UA-.NETStandard 的递归 GetEndpoints-Method 是如何工作的?
- node.js - Mongoose:CastError:在路径“items”中为值“{ value:'x'}”转换为嵌入失败
- java - 如何用 Java 绘制一个 ASCII 楼梯?
- npm - 如何使用 IIS 基本身份验证通过 Azure DevOps Server 2019 工件对 npm 进行身份验证
- c# - 我不明白基类的继承