zl程序教程

您现在的位置是:首页 >  前端

当前栏目

使用Angular的http client发送请求,请求response总是被当成json类型处理

AngularHTTPJSONJSON 处理 类型 请求 发送
2023-09-14 09:04:02 时间

奇怪的问题,我的req.responseType字段没有显式赋值,而默认值为json:

这个默认值是在哪里填充的呢?

调试代码,http.js的第1669行有这个默认的逻辑:

解决方案:下图第26行

responseType: 'text' as 'json'

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

const ENDPOINT = "http://localhost:3000/echo?data=";

@Component({
  selector: 'jerryform',
  template: `
    <input type="text" [formControl]="favoriteColorControl">
  `
})
export class ReactFormComponent implements OnInit  {

  constructor(private http:HttpClient){
  }
  ngOnInit(): void {

    const headers: HttpHeaders = new HttpHeaders({
      'Accept': 'text/html',
    });
    
    const options = {
      headers: headers,
      responseType: 'text' as 'json'
    }
    this.favoriteColorControl.valueChanges.subscribe(
      (value) =>{
        console.log('new value: ' + value);
        var $http = this.http.get('http://localhost:3000/angular/' + value, options);
        
        $http.subscribe(
          (response)=>console.log('response from http: ' + response),
          (error)=>console.log('error: ' + error));
      }
    )
  }
  favoriteColorControl = new FormControl('');
}

参考issue

更多Jerry的原创文章,尽在:“汪子熙”: