代码之家  ›  专栏  ›  技术社区  ›  Manfice

rxjs从第二个请求返回值

  •  -1
  • Manfice  · 技术社区  · 7 年前

    类似这样:

    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

    1 回复  |  直到 7 年前
        1
  •  0
  •   Jota.Toledo    7 年前

    要从一个流映射到另一个流,可以使用 mergeMap switchMap

    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
    }