标签: angular-httpclient

Angular 6+ httpClient 中哪个响应状态代码会进入 catchError?

在 Angular 6+ httpClient 中,可以将请求配置为获取完整响应。

可观察到的响应可以通过管道传输到mapcatchError运算符中。

执行何时通过map运算符以及何时执行catchError

它取决于响应状态代码吗?

例如,如果response.status === 200然后转到map,否则转到catchError?

如果不仅状态 200 转到map,那么还有哪些?

会进入哪些状态catchError

getData(): Observable<[]> {
    return this.http.get(this.apiUrl, {observe: 'response'}).pipe(
        map((response: HttpResponse<any>) => {  
            return response.status === 200;
        }),
        catchError((errorResponse: HttpErrorResponse) =>
            // which value may be logged here?
            console.log(errorResponse.status);
            of(false);
        ));
}

Run Code Online (Sandbox Code Playgroud)

angular angular-httpclient rxjs6

3
推荐指数
1
解决办法
5410
查看次数

带有多部分表单的 Angular 后请求具有错误的内容类型

我正在使用以下函数将文件上传到具有 Angular 7 HttpClient 的服务器

  pushFileToStorage(productId, key, file: File): Observable<any> {
    let formdata: FormData = new FormData();

    formdata.append('prod', file);
    let url_ = '/admin5/api/v1/product/images/upload?';
    url_ += "productId=" + encodeURIComponent("" + productId) + "&";
    url_ += "kind=" + encodeURIComponent("" + key);

    return this.http.post(url_,formdata);
  }
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是 HttpClient 设置了错误的内容类型标头(application/json 而不是“multipart/form-data”),因此服务器无法读取文件。这是我在开发者工具上看到的

在此处输入图片说明

在此处输入图片说明

知道我做错了什么吗?谢谢

file-upload angular angular-httpclient

3
推荐指数
1
解决办法
3123
查看次数

调用第 3 方 API 时处理 CORS

是的,这是一个非常有名的问题,我尝试了之前堆栈溢出 QnA 中提到的许多方法,但没有任何效果。我正在尝试在我的应用程序中使用BANZAI-Cloud API,但它给出了以下错误 在此处输入图片说明

这是我的服务类代码

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import { Observable } from 'rxjs';
import { HttpHeaders } from '@angular/common/http';

@Injectable({providedIn:"root"})
export class PriceTableService{
   
    private priceurl = "https://banzaicloud.com/cloudinfo/api/v1/providers/google/services/compute/regions/asia-east2/products"
    // private priceurl = "https://jsonplaceholder.typicode.com/posts"
    
    constructor(private http:HttpClient){}
    httpOptions = {
        headers: new HttpHeaders({
            'Access-Control-Allow-Methods':'DELETE, POST, GET, OPTIONS',
            'Access-Control-Allow-Headers':'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With',
            'Content-Type':  'application/json',
            'Access-Control-Allow-Origin':'http://localhost:4200'
        })
      };
    getPrices(){
            this.http.get(this.priceurl,this.httpOptions).subscribe(result=>{
            console.log(result);
            return(result);
        })
     }
    ngOnInit() {
    }
}
Run Code Online (Sandbox Code Playgroud)

API可在Angular 应用程序中使用POSTMANCHROME但无法将数据获取到我的 …

cors angular-httpclient

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

收到错误 OK 作为来自 http post 的响应

我正在对节点服务器进行 api 调用。这是一个后调用,但我收到错误作为响应,但 firebase 上的数据发生了变化。

const header : HttpHeaders = new HttpHeaders()
header.append('Content-Type', 'application/x-www-form-urlencoded')

this.http.post('http://localhost:3000/s/getKey', { seqKey : 'invoices' }, {
  headers : header
}).subscribe(data => {
  console.log(data)
})
Run Code Online (Sandbox Code Playgroud)

更新

错误图像

angular angular-httpclient

3
推荐指数
1
解决办法
7032
查看次数

如何在不使用 HttpIntercepter 的情况下在 Angular 中获取自定义响应标头

我没有在 Angular 项目中使用 HttpIntercepter,并且我想在出现错误时检索一些自定义响应标头。我{ observe: 'response' }在 POST API 调用中尝试过:

post(url, data = ''): Observable<any> {
  url = this.baseApiUrl + url;
  const headers = this.createHttpHeaders();
  const body = JSON.stringify(data);
  return this.http.post(url, body, {headers: headers, observe: 'response'}).pipe(catchError(HttpClientHelper.handleError));
}
Run Code Online (Sandbox Code Playgroud)

但我只收到 4 个标头:

error.headers.keys().map( (key) => console.log(key + ':' + error.headers.get(key)));

回报

cache-control: no-cache, no-store, max-age=0, must-revalidate content-length: 0 expires: 0 pragma: no-cache

但是,x-不会返回带有前缀的自定义响应标头。是否有任何配置可以检索自定义响应标头?

在此输入图像描述

spring-boot angular angular-httpclient

3
推荐指数
1
解决办法
2231
查看次数

Angular 8 - 仅在组件内显示加载旋转器

我正在构建一个 SPA,其中主页将包含多个组件。我希望每个组件都有一个加载微调器,没有覆盖层,仅显示在组件内。

我已经实现了ng-http-loader 6.0.1,但它创建了一个覆盖层,并且微调器显示在整个页面上。我没有找到任何选项可以强制它留在该特定组件内。

如果没有,最好的方法是什么?对微调器进行硬编码,当http请求返回结果时,用结果替换微调器?我认为必须有更好的方法来做到这一点。

http使用的示例调用@angular/common/http HttpClient

private startHttpRequest = () => {
this.http.get('/TestUrl/')
  .subscribe(res => {
    console.log(res);
  });
Run Code Online (Sandbox Code Playgroud)

}

我用来SignalR显示和更新结果

signalr angular-http-interceptors angular angular-httpclient

3
推荐指数
1
解决办法
3万
查看次数

Angular 顺序 HTTP Rest 请求

我在 Angular 8 中有以下代码:

fetchMedia() {
    this.mediaDetails.forEach(entry => {
        this.fetchSingleMedia(entry); // NEED TO MAKE THIS SEQUENTIAL
    }
  });
}

fetchSingleMedia(entry) {

  this.mediaService.getMedia(entry).subscribe(
    (data) => {
       // MY LOGIC HERE
    },
    error => {}
  );
}
Run Code Online (Sandbox Code Playgroud)

fetchSingleMedia方法也被代码的其他部分使用。我想将逻辑保留在 fetchSingleMedia 本身中

现在,如果我必须依次向fetchSingleMedia方法发出多个请求,我需要如何修改fetchSingleMedia方法和调用它的方式?也许使用 async/await/promise 或 rxjs?

编辑:

使用concat,在收到第一个响应之前发送第二个请求。我希望在收到第一个请求的响应后发出第二个请求

http rxjs angular angular-httpclient

3
推荐指数
1
解决办法
2848
查看次数

Angular URLSearchParams 与 HttpParams

以前我使用过

import { Http, Response, Headers, URLSearchParams  } from "@angular/http";
Run Code Online (Sandbox Code Playgroud)

对于 API 调用

getprojectscount(city, param){
let urlSearchParams = new URLSearchParams();
  urlSearchParams.set('limit', param.limit );
  urlSearchParams.set('limitrows', param.limitrows );
  urlSearchParams.set('locality', param.locality );

return this.http
    .get(this.myapiurl + city + "?", { search: urlSearchParams })
    .pipe(map(response => response.json().Counts));

}

Run Code Online (Sandbox Code Playgroud)

在此 URLSEARCHPARAMS 方法中,它运行良好。-> 因为当我们传递参数时。仅当需要时,它才会传递给 urlSearchParams 。

目前正在使用

import {  HttpErrorResponse, HttpParams } from '@angular/common/http';
Run Code Online (Sandbox Code Playgroud)

AND 来到 HttpParams。当我使用这个 HTTPPARAMS 时,每次每个参数都通过 api 传递,如果它也为 null。

对于 API 调用

getprojectcount(city,param){
let params = new HttpParams();
params = params.append('limit', param.limit);
 params …
Run Code Online (Sandbox Code Playgroud)

angular-http angular angular-httpclient angular9

3
推荐指数
1
解决办法
2259
查看次数

角,HttpClient;'Observable' 类型不存在属性 '.shareReplay'

对不起,如果这是一个明显的问题。我正在关注本教程:https : //blog.angular-university.io/angular-jwt-authentication/

我在教程中创建了服务,但它告诉我属性 '.shareReplay' 不存在于类型 'Observable',我假设我的导入不正确,但我似乎无法找到正确的。

import {Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {User} from "./model/user";

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

  constructor(private http: HttpClient) {
  }

  login(username: string, password: string){
    return this.http.post<User>('/login', {username, password})
      .shareReplay();
  }
}
Run Code Online (Sandbox Code Playgroud)

typescript angular angular-httpclient

3
推荐指数
1
解决办法
670
查看次数

使用 StreamSaver.js 流式传输大型 blob 文件

我正在尝试使用Angular 组件中的StreamSaver.js将大型数据文件从服务器直接下载到文件系统。但在~2GB之后就会出现错误。数据似乎首先被传输到浏览器内存中的 blob 中。而且可能有 2GB 的限制。我的代码基本上取自 StreamSaver 示例。知道我做错了什么以及为什么文件没有直接保存在文件系统上吗?

服务:

public transferData(url: string): Observable<Blob> {
    return this.http.get(url, { responseType: 'blob' });
}
Run Code Online (Sandbox Code Playgroud)

成分:

download(url: string) {
    this.extractionService.transferData(url)
      .subscribe(blob => {
        const fileStream = streamSaver.createWriteStream('data.tel', {
          size: blob.size
        });
        const readableStream = blob.stream();
        if (window.WritableStream && readableStream.pipeTo) {
          return readableStream
            .pipeTo(fileStream)
            .then(() => console.log("done writing"));
        }
        const writer = fileStream.getWriter();
        const reader = readableStream.getReader();
        const pump = () =>
          reader.read()
            .then(res => res.done ? writer.close() : writer.write(res.value).then(pump));
        pump();
      });
} …
Run Code Online (Sandbox Code Playgroud)

javascript angular angular-httpclient

3
推荐指数
1
解决办法
8609
查看次数