Angular 如何在路由之前等待订阅事件完成
我目前正在做一个POST方法,并使用一些参数路由我的应用程序,但问题似乎是,应用程序在POST方法完成之前路由,并带有一个响应 我的职能:Angular 如何在路由之前等待订阅事件完成,angular,http,post,routing,rxjs,Angular,Http,Post,Routing,Rxjs,我目前正在做一个POST方法,并使用一些参数路由我的应用程序,但问题似乎是,应用程序在POST方法完成之前路由,并带有一个响应 我的职能: let responseBody; let postUploads = function() { return this.http.post(url, uploadFile).pipe((response: any) => this.responseBody = response); } postUplo
let responseBody;
let postUploads = function() {
return this.http.post(url, uploadFile).pipe((response: any) => this.responseBody = response);
}
postUploads().subscribe(() => this.router(['/inbox], { queryParams: {file: responseBody} }));
正在发生的问题是,它在“responseBody”作为POST的响应返回之前到达路由
如何让它等待响应返回,然后再路由用户?您引用了错误的
响应库
请尝试以下方法:
this.http.post(url, uploadFile)
.subscribe(responseBody => this.router(['/inbox'], { queryParams: { file: responseBody } }))
想法是让可观察的输出(例如http.post()
)流经可观察链。我认为局部变量responseBody在这里是不必要的。您可以在subscribe方法中直接获取responseBody的引用。我已经删除了不必要的代码,请检查并让我知道它是否有效
let postUploads = function() {
return this.http.post(url, uploadFile);
}
postUploads().subscribe((responseBody) => this.router(['/inbox], { queryParams: {file: responseBody} }));
这里有几个问题
let responseBody;
设postoploads=function(){
返回this.http.post(url,uploadFile).pipe((响应:any)=>this.responseBody=response);
}
在这段代码中,因为您是使用function(){}
语法声明函数,this
将引用函数本身this.http
将是未定义的
此外,您似乎正在尝试使用表达式this.responseBody=response
设置局部变量responseBody
这也是对管道的错误使用。管道接受RxJS操作符,例如map
,tap
,等等。它不接受这样的回调
this.router(['/inbox],{queryParams:{file:responseBody}})
在此代码中,您没有以正确的方式调用路由器。我猜你的意思是this.router.navigate(['/inbox],{queryParams:{file:responseBody}})
固定版本
您的代码可以简化为以下内容:
this.http.post(url,uploadFile).subscribe((响应:any)=>{
this.router.navigate(['/inbox'],{queryParams:{file:response}});
});
当收到响应时,它订阅可观察对象并执行导航。我不知道响应的数据类型是什么,但是如果它是某种blob,你可能不想把它放在url中。hmm这个方法也不起作用……所以路由先用responseBody更改,没有响应,然后用响应附加第二次。