首页 > 解决方案 > 如何在路由之前等待订阅事件完成

问题描述

我目前正在使用 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的响应返回之前进入路由

在路由用户之前,如何让它等待响应返回?

标签: angularhttppostroutingrxjs

解决方案


你在这里有几个问题。

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 中。


推荐阅读