Angular 6: How to set response type as text while making http call

后端 未结 6 1014
無奈伤痛
無奈伤痛 2020-11-28 09:05

I trying to make http request to the spring rest API.. API returns a string value (\"success\" or \"fail\")... but I dont know how to set the response type as string value w

相关标签:
6条回答
  • 2020-11-28 09:33

    Have you tried not setting the responseType and just type casting the response?

    This is what worked for me:

    /**
     * Client for consuming recordings HTTP API endpoint.
     */
    @Injectable({
      providedIn: 'root'
    })
    export class DownloadUrlClientService {
      private _log = Log.create('DownloadUrlClientService');
    
    
      constructor(
        private _http: HttpClient,
      ) {}
    
      private async _getUrl(url: string): Promise<string> {
        const httpOptions = {headers: new HttpHeaders({'auth': 'false'})};
        // const httpOptions = {headers: new HttpHeaders({'auth': 'false'}), responseType: 'text'};
        const res = await (this._http.get(url, httpOptions) as Observable<string>).toPromise();
        // const res = await (this._http.get(url, httpOptions)).toPromise();
        return res;
      }
    }
    
    0 讨论(0)
  • 2020-11-28 09:35

    Use like below:

      yourFunc(input: any):Observable<string> {
    var requestHeader = { headers: new HttpHeaders({ 'Content-Type': 'text/plain', 'No-Auth': 'False' })};
    const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
    return this.http.post<string>(this.yourBaseApi+ '/do-api', input, { headers, responseType: 'text' as 'json'  });
    

    }

    0 讨论(0)
  • 2020-11-28 09:43

    To get rid of error:

    Type '"text"' is not assignable to type '"json"'.

    Use

    responseType: 'text' as 'json'

    import { HttpClient, HttpHeaders } from '@angular/common/http';
    .....
     return this.http
            .post<string>(
                this.baseUrl + '/Tickets/getTicket',
                JSON.stringify(value),
            { headers, responseType: 'text' as 'json' }
            )
            .map(res => {
                return res;
            })
            .catch(this.handleError);
    
    0 讨论(0)
  • 2020-11-28 09:52

    On your backEnd, you should add:

    @RequestMapping(value="/blabla",  produces="text/plain" , method = RequestMethod.GET)
    

    On the frontEnd (Service):

    methodBlabla() 
    {
      const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
      return this.http.get(this.url,{ headers, responseType: 'text'});
    }
    
    0 讨论(0)
  • 2020-11-28 09:53

    By Default angular return responseType as Json, but we can configure below types according to your requirement.

    responseType: 'arraybuffer'|'blob'|'json'|'text'
    

    Ex:

    this.http.post(
        'http://localhost:8080/order/addtocart', 
        { dealerId: 13, createdBy: "-1", productId, quantity }, 
        { headers, responseType: 'text'});
    
    0 讨论(0)
  • 2020-11-28 09:57

    You should not use those headers, the headers determine what kind of type you are sending, and you are clearly sending an object, which means, JSON.

    Instead you should set the option responseType to text:

    addToCart(productId: number, quantity: number): Observable<any> {
      const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
    
      return this.http.post(
        'http://localhost:8080/order/addtocart', 
        { dealerId: 13, createdBy: "-1", productId, quantity }, 
        { headers, responseType: 'text'}
      ).pipe(catchError(this.errorHandlerService.handleError));
    }
    
    0 讨论(0)
提交回复
热议问题