首页 > 解决方案 > 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"
        }
    ]
}

标签: angularobservablebehaviorsubject

解决方案


使用管道有效。

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) )
        )
    }
}

推荐阅读