【问题标题】:Angular routing inside a http post Observable / subscribehttp post Observable / subscribe 中的角度路由
【发布时间】:2021-04-04 09:10:47
【问题描述】:

我正在尝试将用户定向到 responsehttpClient.post 请求中的仪表板。页面导航“很好”(它显示在 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 函数对我不起作用。完整功能中注释掉的整页重新加载 (window.top.location.href = "https://" + window.location.host;) 有效,但它不是角度方式。

【问题讨论】:

    标签: angular angular-router angular10 angular-observable


    【解决方案1】:

    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 子句。这应该可以解决它。

    您始终可以在代码中使用debugger 来查看函数何时执行。如果您没有完全了解subscribe 的哪一部分执行的时间,我建议您多做几次。

    【讨论】:

      猜你喜欢
      • 2017-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-06
      • 2017-02-10
      • 1970-01-01
      • 2015-06-13
      • 2016-04-07
      • 2017-04-23
      相关资源
      最近更新 更多