簡體   English   中英

Angular routing inside a http post Observable / subscribe

[英]Angular routing inside a http post Observable / subscribe

我正在嘗試將用戶定向到httpClient.post請求response中的儀表板。 該頁面導航“很好”(它顯示在 url 欄上)但組件 DOM 的大多數元素未加載。

這是 service.ts 中的帖子:

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';

const baseUrl = 'https://my-api.com';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private httpClient: HttpClient) { }

  postSomeData(data): Observable<any> {
    return this.httpClient.post(baseUrl + '/postSomeData', data)
  }

這就是我在組件中使用它的方式:

this.apiService.postSomeData(params)
            .subscribe(
              async response => {
                response = await response;
                if(response.response == 'success'){
                  // success logic

                }else{
                  // failure message
                }
              },
              error => {
                // error logic
              },
              () => {
                // window.top.location.href = "https://" + window.location.host;
                this.router.navigate(["/dashboard"]);
              });

subscribe完成並且路由器導航到儀表板時,這是我得到的儀表板 DOM 的不完整加載: 在此處輸入圖像描述

如果我將導航( this.router.navigate(["/dashboard"]); )放在訂閱之外的任何地方,或者我手動或以編程方式重新加載頁面( window.top.location.href = "https://" + window.location.host; ) 頁面 (DOM) 加載得很好: 在此處輸入圖像描述

那么我如何在訂閱中實現導航並擁有儀表板組件的完整 DOM 加載呢? 顯然,訂閱中的complete function 對我不起作用。 在完整的 function 中注釋掉整頁重新加載( window.top.location.href = "https://" + window.location.host; )有效,但它不是 angular 方式。

subscribe返回的第一個響應在 HTTP 方法成功時執行,因此無需檢查響應。

第二個響應在出錯時執行。

因此,實際上您只需執行以下操作即可大大簡化您的代碼:

this.apiService.postSomeData(params)
            .subscribe(
              () => {
                // success logic, HTTP statuscode 20X
              },
              () => {
                // error logic, when a HTTP error has been thrown
              },
              () => {
                // executed when the HTTP function has been completed, doesn't matter whether success or error
                this.router.navigate(["/dashboard"]);
              });

我認為問題與asyncif子句有關。 沒有理由在那里使用asyncif -clause。 這應該解決它。

您始終可以在代碼中使用debugger來查看 function 何時執行。 如果您沒有完全了解subscribe的哪一部分何時執行,我建議您多做幾次。

暫無
暫無

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

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