Angular HttpClient 纯文本 (text/plain) 最小示例

为了使 Angular 的 HttpClient 处理纯文本响应而不导致错误,你需要在 options(这是 .get() 的第二个参数)中设置 responseType: 'text'。否则,Angular 将尝试解析纯文本响应,即使响应 MIME 类型设置为 text/plain

plaintext_service.ts
getPlaintext(command: string): Observable<string> {
  return this.http.get(`/api/text`, { responseType: 'text' });
}

完整服务示例

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

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

  constructor(private http: HttpClient) { }

  getPlaintext(command: string): Observable<string> {
    return this.http.get(`/api/text`, { responseType: 'text' });
  }
}

Check out similar posts by category: Angular, Typescript