簡體   English   中英

如何在路由之前等待訂閱事件完成

[英]how to wait for the subscribe event to finish before routing

我目前正在使用 POST 方法並使用一些參數路由我的應用程序,但問題似乎是應用程序在 POST 方法完成之前路由並帶有響應。

我的 function:

    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() { }語法聲明了 function, this將引用 function 本身。 this.http將未定義。

此外,您似乎正在嘗試使用表達式this.responseBody = response responseBody

這也是pipe的錯誤使用。 Pipe 接受 RxJS 運算符,例如maptap等。它不接受這樣的回調。

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

您引用了錯誤的responseBody

試試這個:

  this.http.post(url, uploadFile)
    .subscribe(responseBody => this.router(['/inbox'], { queryParams: { file: responseBody } }))

這個想法是讓 observable 的 output(例如http.post() )流過 observable 鏈。

我認為這里不需要局部變量 responseBody。 在 subscribe 方法中可以直接獲取 responseBody 的引用。 我已經刪除了不必要的代碼,請檢查並讓我知道它是否有效。

    let postUploads = function() {
      return this.http.post(url, uploadFile);
    }

    postUploads().subscribe((responseBody) => this.router(['/inbox], { queryParams: {file: responseBody} }));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM