angular - 如何在路由之前等待订阅事件完成
问题描述
我目前正在使用 POST 方法并使用一些参数路由我的应用程序,但问题似乎是应用程序在 POST 方法完成之前路由并带有响应。
我的功能:
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的响应返回之前进入路由
在路由用户之前,如何让它等待响应返回?
解决方案
你在这里有几个问题。
let responseBody;
let postUploads = function() {
return this.http.post(url, uploadFile).pipe((response: any) => this.responseBody = response);
}
在此代码中,因为您使用function() { }
语法声明函数,所以this
将引用函数本身。this.http
将是未定义的。
此外,您似乎正在尝试responseBody
使用表达式设置局部变量this.responseBody = response
。
这也是不正确的使用pipe
. Pipe 接受 RxJS 运算符,例如map
,tap
等。它不接受这样的回调。
this.router(['/inbox], { queryParams: {file: responseBody} })
在此代码中,您没有以正确的方式调用路由器。我怀疑你的意思是this.router.navigate(['/inbox], { queryParams: {file: responseBody} })
;
固定版本
您的代码可以简化为以下内容:
this.http.post(url, uploadFile).subscribe((response: any) => {
this.router.navigate(['/inbox'], { queryParams: {file: response } });
});
这订阅了 observable 并在收到响应时执行导航。我不知道数据类型response
是什么,但如果它是某种 blob,你可能不想把它放在 url 中。
推荐阅读
- java - Spring Integration - 在消息中添加自定义标头
- javascript - 什么是后代运算符?它是用javascript还是其他任何语言?
- dart - 我的 Darkcode 显示错误“未使用局部变量 'choice' 的值”
- android - 即使应用程序已从内存中删除,也可以监听传入的 SMS 消息
- javascript - 在 ReactJS 中以手风琴风格呈现无限数量的项目?
- probability - 在扑克中获得特定卡片的概率
- c# - 如何在 StartUp.cs 中为 .net core 3.1 打印进程名称
- laravel - Laravel 使用两个模型关系创建另一个模型对象
- typescript - NextJS & Typescript getInitialProps linting 错误(返回类型)
- r - 当我尝试网络抓取表格时,为什么会出现矩阵错误?