Search code examples
angularrxjsobservableangular-services

How to return observable of string


Have an api method that returns a simple string. I am implementing a method in my angular service that needs to return an obserable

The simple string doesnt map directly into the observable. How can I return an observable with the simple string result from the api?

public setLineItemListApproval(lines : OrderLinesModel) : Observable<string>{

    let actionUrl = this.apiBaseURL + '/mycontroller/actionmethod1';
    const httpOptions = {
        headers: new HttpHeaders({
            'Content-Type':  'application/json'
        })
    };

    return this.httpClient.post<string>(actionUrl, lines, httpOptions).pipe(catchError(this.handleError));

}

Solution

  • You need to

    • Include responseType: 'text in the options argument
    • Inline the options with the call
    • Use the non-generic overload of post as responseType: 'text' option now dictates which one is used as well as the return type in the Observable response
    public setLineItemListApproval(lines : OrderLinesModel) : Observable<string>{
    
        let actionUrl = this.apiBaseURL + '/mycontroller/actionmethod1';
        return this.httpClient.post(actionUrl, lines, {
            headers: new HttpHeaders({
                'Content-Type':  'application/json'
            }),
            responseType: 'text'
        }).pipe(catchError(this.handleError));
    
    }