标签: angular-httpclient

带有重试和延迟的 Angular HttpClient 请求发送额外的请求然后取消它

我正在尝试使用Angulars HttpClient服务来发出请求,并进行多次尝试和延迟。该代码有效,但我注意到在 devTools 网络水龙头中,最终发送并取消了额外的请求。我在这里做错了什么是代码:

return this.http.post<LoginSuccessPayload>('/api/auth/signin', payload).pipe(
  retryWhen(errors => {
    return errors.pipe(
      mergeMap((er: any) => {
        if (er.status === 504 || er.status === 503) {
          return of(er.status).pipe(delay(1000));
        }
        return _throw({message: er.error.message || 'Notification.Core.loginError'});
      }),
      take(3),
      concat(_throw({message: 'Notification.Core.networkError'}))
    );
  })
);
Run Code Online (Sandbox Code Playgroud)

这是Firefox和Chrome网络选项卡的图像,应该有三个请求,但它生成了四个请求并取消了最后一个请求 在此输入图像描述

javascript rxjs angular angular-httpclient

2
推荐指数
1
解决办法
9522
查看次数

以角度形式保留 http 调用的顺序

我正在尝试使用我在此处找到的几种方法来解决我面临的订单问题,但没有成功。

我有一个方法,可以为传单层数组加载一些数据:

private loadSelectedTileLayersCapabilities(): void {

        let tempTileLayer;

        this.selectedTileLayerIds.forEach(
            (selectedTileLayer: string) => {
                tempTileLayer = this.getTileLayerById(selectedTileLayer);

                this.capabilitiesService.getTileLayerDimensions(tempTileLayer.url, tempTileLayer.name, tempTileLayer.id)
                .subscribe(
                    dimensions => this.displayNewTileLayer(dimensions)
                );
            }
        );
    }
Run Code Online (Sandbox Code Playgroud)

然后我有一个方法,调用http发生在其中:

public getTileLayerDimensions(urlToFormat: string, tileLayerName: string, tileLayerId: string): Observable<Dimensions> {

        const capabilitiesUrl = `serviceUrl`;

        return this.httpClient.get(capabilitiesUrl, {responseType: "text"})
            .map(res => {

                // Doing stuff with data

                return dataForLayer;
            });

    }
Run Code Online (Sandbox Code Playgroud)

问题是,该displayNewTileLayer(dimensions)方法是按随机顺序调用的。有没有办法保留数组中项目的存储顺序 selectedTileLayerIds?

rxjs angular angular-httpclient

2
推荐指数
1
解决办法
4349
查看次数

如何防止在 Angular HttpClient.post 方法中发送空字段?

当我想将信息作为 post 方法发送到我的 Rest API 时,Angular 会发送空字段,随后我的数据库会保存空值。

但我想阻止它,并且我不想将空字段从我的 Angular 发送到我的后端。

例如,在下面的示例中,Angular 在entityTypeName 字段中发送“”,不幸的是,Postgres DB 将保存空而不是空。

{ 
   createdAt: "2019-01-11T13:59:52.311678"
   entityTypeName: ""
   id: "1bd46fce-fc6f-410f-acaf-74d5964cf92b"
   updatedAt: "2019-01-11T13:59:52.311678"
   updatedBy: "admin@admin.com"
   version: 0 
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种通用的解决方案,以防止在所有情况下在 Angular 端发送空值。

angular angular-httpclient

2
推荐指数
1
解决办法
3447
查看次数

无法在 Angular 5 中获取本地 json 文件 - 持续出现 404 错误

我已经阅读了我能找到的所有其他关于此的文章或帖子。我一生都无法弄清楚这个简单的任务我哪里出了问题。(特别是按照这个例子。)我一定做了一些明显愚蠢的事情,但我已经看这个很久了,我看不到它。

我在 asset/mockData 中有一个名为 isRecognized.json 的 json 文件。我已将 mockData 目录添加到我的 webpack 配置文件中,因此它包含在 /dist 目录中。如果我访问 http:localhost:4200/assets/mockData/isRecognized.json 我可以看到该文件,所以我知道它可用。

但是,当我尝试使用 HTTP 客户端检索文件时,无论我如何尝试,它都会抛出 404。

编辑:我使用的是 Webpack,而不是 Angular CLI。

应用程序组件.ts

import { MyService } from './services/my.service';
import { Component, OnInit, Renderer2 } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

/*
* Main app component that houses all views.
*/
@Component({
    selector: 'app-comp',
    templateUrl: './app.component.html'
})

export class AppComponent implements OnInit {

    constructor(
        private route: ActivatedRoute, private service: MyService
    ) {}

    ngOnInit() { …
Run Code Online (Sandbox Code Playgroud)

json rxjs typescript angular angular-httpclient

2
推荐指数
1
解决办法
2913
查看次数

Angular 6 HttpClient Post 未命中 DotNet Core 2.2 API 控制器中的 API Post 方法

我已从 MVC/AngularJS 1.x 升级到 DotNet Core 2.2/Angular 6.x。与@Angular/common/http

大多数情况下,这都是轻而易举的事,但 Web API 却让我很受不了。我在几分钟内就开始工作,但我花了一周的时间尝试了一切才能让网络帖子工作。

我在这里所做的事情很容易复制。

  1. 进入 Visual Studio 17 并单击“文件/新建项目”

  2. 选择已安装/Visual C#/.NET Core

  3. 选择模板:ASP.NET core Web Application

  4. 在辅助屏幕上,将顶部的下拉菜单设置为 .NET Core 和 ASP.NET Core 2.2

  5. 选择红盾“A”角模板

  6. 让项目拉下依赖关系并重建。

一切都是 Microsoft 提供的开箱即用演示应用程序,除了:

  1. 将按钮添加到屏幕上。

  2. 将代码添加到 .ts 以调用 API 控制器

  3. 将输入参数添加到控制器中的 get 方法中

  4. 向控制器添加一个非常简单的 post 方法

我也在尝试获取 DotNet Core 2.0/Angular 4.x。使用 @angular/http 可以得到完全相同的结果。获取非常简单,但我已经尝试了所有配置才能使帖子正常工作。我也会为其他版本发布类似的帖子。现在,我只是尽我所能地工作并把 AngularJS 1.x 抛在身后。

import { Component, Inject } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders  } from '@angular/common/http';

@Component({
  selector: 'app-fetch-data',
  templateUrl: './fetch-data.component.html'
}) …
Run Code Online (Sandbox Code Playgroud)

c# controller .net-core angular angular-httpclient

2
推荐指数
1
解决办法
4420
查看次数

添加查询参数到http请求时出错

我正在使用模拟数据和 InMemoryDbService,如英雄之旅示例所示。当我不传递 HttpParams 时,加载数据工作正常。添加参数后,我会收到 500 响应,正文中包含以下错误:{error: "collection.filter is not a function"}我已使用 get 请求中的数据填充表,如下所示:

组件代码:

@Component({
  selector: 'app-adapter',
  templateUrl: './adapter.component.html',
  styleUrls: ['./adapter.component.css']
})
export class AdapterComponent implements OnInit {
  dataSource = new MatTableDataSource<Request>();
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator;
  constructor(private api: BaseServiceApi) {}

  ngOnInit() {
    this.refresh(); // this works with no params and populates my table
  }

  refresh(params?) {
    this.getRequests(params)
      .subscribe(reply => {
          this.dataSource.data = reply.payload as Request[];
          this.dataSource.sort = this.sort;
          this.dataSource.paginator = this.paginator;
          this.pageSize = this.paginator.pageSize;
        }
      ); …
Run Code Online (Sandbox Code Playgroud)

angular angular-httpclient angular-in-memory-web-api

2
推荐指数
1
解决办法
1626
查看次数

Angular http.get() url 作为原始 HTML

我正在为一个任务创建一个站点,我想在其中动态加载一些数据。问题是,数据只是来自网站,没有 API 或任何东西。有什么方法可以在 angular 中使用 http.get 将整个网站作为原始 HTML 提取,然后我可以解析信息吗?

谢谢

angular angular-httpclient

2
推荐指数
1
解决办法
4406
查看次数

在功能模块中导入 HttpClientModule

该文档上HttpClientModule说:

在您可以使用 HttpClientModule 之前,您需要导入 Angular HttpClientModule。大多数应用程序都在根 AppModule 中执行此操作。

  1. 在哪些情况下我们要导入HttpClientModule到功能模块中?
  2. 如果我们将它导入到多个功能模块中,而这些功能模块又被导入到根模块中,会发生什么?
  3. 当我们在一个应用程序中有几十个模块,其中一些需要HttpClientModule,而我们HttpClientModule只想导入这几个模块时,这是一个正确的用例吗?

angular-module angular angular-httpclient

2
推荐指数
1
解决办法
1257
查看次数

没有重载匹配这个调用。最后一次重载给出了以下错误。类型 '"text"' 不能分配给类型 '"json"'

我正在尝试使用 Angular 从我的 API 获取 HTML 页面,并在标头中使用 JWT 令牌。但是,如果我不指定文本类型,编译器会发出无法解析的错误(然后它会尝试将 HTML 解析为 JSON),因此我需要指定我的响应类型。

这是我的 component.ts:

  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': 'Bearer TOKENHERE'
    })
  };
  constructor(private http: HttpClient) { }

  ngOnInit() {


  }
  fetchDashboard() {
    this.http.get('http://localhost:3000/avior/dashboard', {responseType: 'text', this.httpOptions,}).subscribe(j => console.log(j));
}
}
Run Code Online (Sandbox Code Playgroud)

我尝试将内容类型删除或更改为 text/html ,但没有任何效果。


我的 API 响应:

<html><head><title>Dashboard</title></head><body><h1>Dashboard works!</h1></body></html>

javascript xmlhttprequest jwt angular angular-httpclient

2
推荐指数
2
解决办法
6998
查看次数

Angular 9 HttpErrorResponse“JSON.Parse错误”,而响应正常

为什么这会引发错误?

 deleteUser(userId: string) {
    this.dataService.deleteUser(userId).subscribe((response: string) => {
      console.log(response);
    });
  }
Run Code Online (Sandbox Code Playgroud)

“SyntaxError:JSON 中的意外标记 f 在 JSON.parse () 在 XMLHttpRequest.onLoad (https://localhost:5001/vendor.js:34968:51) 在 ZoneDelegate.invokeTask (https://localhost:5001) 的位置 1 /polyfills.js:412:35) 在 Object.onInvokeTask (https://localhost:5001/vendor.js:72879:33) 在 ZoneDelegate.invokeTask (https://localhost:5001/polyfills.js:411:40) )在Zone.runTask(https://localhost:5001/polyfills.js:180:51)在ZoneTask.invokeTask [作为调用](https://localhost:5001/polyfills.js:493:38)在invokeTask( https://localhost:5001/polyfills.js:1634:18) 在 XMLHttpRequest.globalZoneAwareCallback (https://localhost:5001/polyfills.js:1671:25)"

响应是纯字符串值,状态为 200。

在此输入图像描述

在此输入图像描述

我错过了什么?

json typescript angular angular-httpclient

2
推荐指数
1
解决办法
4460
查看次数