Angular请求返回非json数据详解

博客介绍了Angular请求返回数据的处理方法。Angular默认对返回数据做JSON解析,若返回非JSON数据会报错,此时需设置responseType头信息。Get和Post请求处理大体相同,还提到请求需调用.subscribe()方法才执行,以及不同数据格式的处理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Angular请求返回的数据默认是做json解析处理,如果返回的数据不是json格式,就会报错,如下:

Unexpected token O in JSON at position 0

!](https://img-blog.csdnimg.cn/20190522095409421.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMjQ4NTI5,size_16,color_FFFFFF,t_70)

这时候就要对请求的返回数据格式进行处理,如下:
如果需要返回非JSON数据,则需要在请求时设置responseType头信息为text:

Get请求:

  return this.http.get(url, {responseType: 'text'})

同时,说明下angular请求好像只有调用.subscribe()方法才可以执行,我这是请求是在service里面写的,在component里面调用的。
service:

   getdataList(){
    this.genanUrl ="http://localhost:4200/genan/api/MCU32/getDataCollect?jsonSql={sequence_id:'00022'}&limit=500&skip=0";
    return this.http.get(this.genanUrl,{responseType: 'text'});
   }

component:

  getVersioninfo(){
    console.log('getVersioninfo-----');
    this.datainfoService.getDataCount().subscribe(result =>{
      console.log('result111:' + result);
    })

切记不要将{responseType: ‘text’}放在请求头header或params中,它应该是单独的一项,否则无法生效。源码如下:

    /**
     * Constructs a `GET` request that interprets the body as a text string
     * and returns the response as a string value.
     *
     * @param url     The endpoint URL.
     * @param options The HTTP options to send with the request.
     *
     * @return An `Observable` of the response, with the response body of type string.
     */
    get(url: string, options: {
        headers?: HttpHeaders | {
            [header: string]: string | string[];
        };
        observe?: 'body';
        params?: HttpParams | {
            [param: string]: string | string[];
        };
        reportProgress?: boolean;
        responseType: 'text';
        withCredentials?: boolean;
    }): Observable<string>;

Post请求:

处理大体相同,只是post请求参数有变化,中间请求body即使是空的也需要传,否则{responseType: ‘text’}就当成了请求body

 return this.http.post(this.genanUrl,{},{responseType: 'text'});

源码如下:

/**
 * Constructs a `POST` request that interprets the body as a text string and
 * returns the response as a string value.
 *
 * @param url The endpoint URL.
 * @param body The content to replace with.
 * @param options HTTP options
 *
 * @return An `Observable` of the response, with a response body of type string.
 */
post(url: string, body: any | null, options: {
    headers?: HttpHeaders | {
        [header: string]: string | string[];
    };
    observe?: 'body';
    params?: HttpParams | {
        [param: string]: string | string[];
    };
    reportProgress?: boolean;
    responseType: 'text';
    withCredentials?: boolean;
}): Observable<string>;

这里的请求返回的数据只是当成text文本处理,如果返回的数据还有其他形式,如:arraybuffer,blob格式处理方法相同,只是将text改成相应格式。下面提供部分源码如下,可以看到 responseType有四种:json,arraybuffer,blob,text

 /**
     * Constructs a `PATCH` request that interprets the body as a JSON object
     * and returns the response in a given type.
     *
     * @param url The endpoint URL.
     * @param body The resources to edit.
     * @param options HTTP options.
     *
     * @return  An `Observable` of the `HttpResponse` for the request,
     * with a response body in the given type.
     */
    patch<T>(url: string, body: any | null, options?: {
        headers?: HttpHeaders | {
            [header: string]: string | string[];
        };
        observe?: 'body';
        params?: HttpParams | {
            [param: string]: string | string[];
        };
        reportProgress?: boolean;
        responseType?: 'json';
        withCredentials?: boolean;
    }): Observable<T>;
    /**
     * Constructs a `POST` request that interprets the body as an as an `ArrayBuffer` and returns
     * an `ArrayBuffer`.
     *
     * @param url The endpoint URL.
     * @param body The content to replace with.
     * @param options HTTP options.
     *
     * @return An `Observable` of the response, with the response body as an `ArrayBuffer`.
     */
    post(url: string, body: any | null, options: {
        headers?: HttpHeaders | {
            [header: string]: string | string[];
        };
        observe?: 'body';
        params?: HttpParams | {
            [param: string]: string | string[];
        };
        reportProgress?: boolean;
        responseType: 'arraybuffer';
        withCredentials?: boolean;
    }): Observable<ArrayBuffer>;
    /**
     * Constructs a `POST` request that interprets the body as a `Blob` and returns the
     * response as a `Blob`.
     *
     * @param url The endpoint URL.
     * @param body The content to replace with.
     * @param options HTTP options
     *
     * @return An `Observable` of the response, with the response body as a `Blob`.
     */
    post(url: string, body: any | null, options: {
        headers?: HttpHeaders | {
            [header: string]: string | string[];
        };
        observe?: 'body';
        params?: HttpParams | {
            [param: string]: string | string[];
        };
        reportProgress?: boolean;
        responseType: 'blob';
        withCredentials?: boolean;
    }): Observable<Blob>;
    /**
     * Constructs a `POST` request that interprets the body as a text string and
     * returns the response as a string value.
     *
     * @param url The endpoint URL.
     * @param body The content to replace with.
     * @param options HTTP options
     *
     * @return An `Observable` of the response, with a response body of type string.
     */
    post(url: string, body: any | null, options: {
        headers?: HttpHeaders | {
            [header: string]: string | string[];
        };
        observe?: 'body';
        params?: HttpParams | {
            [param: string]: string | string[];
        };
        reportProgress?: boolean;
        responseType: 'text';
        withCredentials?: boolean;
    }): Observable<string>;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值