【问题标题】:rxjs return value from second request来自第二个请求的 rxjs 返回值
【发布时间】:2017-09-09 07:43:47
【问题描述】:

我在从第二个请求返回 Observable 时遇到问题。 像这样的:

commandRequest(action:string, commandData:any):Observable<CashDesckResponse>
{
    let command:CashDeskRequest;
    //ask my backend for command
    this.requestCommandString(action, commandData, "POST")
        //this is my response from backend
        .map(r=>r.response).subscribe(my_1_response=>{
        //then i need to send this response data to other server/action 
        //to execute it and return this second response as the result of
        //this method.
        command = new CashDesckRequest(my_1_response);
        return this.server.executeCommand(command).map(return_this=>return_this);
    }); 
};

private requestCommandString(action:string, requestData:any,
                             type:string):Observable<AjaxResponse>{
    return Observable.ajax({
        body:JSON.stringify(requestData),
        method:type,
        url:this._apiServerUrl+action
    }).map(r=>r);
};

我的问题是 commandRequest 从第一个 .map() 返回值。如果我会尝试从内部订阅编译器返回值抛出错误: [ts] 声明类型既不是“void”也不是“any”的函数必须返回一个值。 https://habrastorage.org/web/93b/e6b/17b/93be6b17bf5b46b5847e67deefd6eea1.png

【问题讨论】:

    标签: ajax typescript rxjs


    【解决方案1】:

    要从一个流映射到另一个流,您可以使用 mergeMapswitchMap

    commandRequest(action:string, commandData:any):Observable<CashDesckResponse>
    {
        return this.requestCommandString(action, commandData, "POST")
            .map(r1 => new CashDesckRequest(r1.response)
            // map first response to command instance
            .mergeMap(command =>this.server.executeCommand(command));
            // map the command observable to a new observable
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-22
      • 2023-03-31
      • 1970-01-01
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多