【问题标题】:How to return observable of string如何返回可观察的字符串
【发布时间】:2019-05-09 15:47:02
【问题描述】:

有一个返回简单字符串的 api 方法。我正在我的角度服务中实现一个需要返回可观察对象的方法

简单的字符串不会直接映射到 observable。如何使用 api 的简单字符串结果返回 observable?

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

}

【问题讨论】:

  • 你想在哪里退货?在某些组件中?或者在同一个服务中

标签: angular rxjs observable angular-services


【解决方案1】:

你需要

  • options 参数中包含responseType: 'text
  • 将选项与调用内联
  • 使用post 的非泛型重载作为responseType: 'text' 选项现在指示使用哪一个以及Observable 响应中的返回类型
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));

}

【讨论】:

    【解决方案2】:

    为了完成这个:

    1. 在选项参数中添加 responseType: 'text'

    这个简单的改变应该可以工作

    【讨论】:

    • 在下面查看我的答案。仅添加 responseType: 'text' 会在运行 ng build 时出现错误,因为类型不可分配。如果您想构建代码,您必须完成我在回答中的所有 3 个步骤。
    猜你喜欢
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 2020-05-02
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    相关资源
    最近更新 更多