Angular2 http get issue returning a string
Asked Answered
S

4

8

I have a simple Flask app running that returns a string enter image description here

and my Angular2 code has been cobbled together from various tutorials that I've seen online webservices.services.ts

import { Component, OnInit, Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import {HttpModule} from '@angular/http';
import {JsonpModule} from '@angular/http';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class WebService {
  constructor(private http: Http, private router: Router,private _jsonp: JsonpModule) { }

 public getDataFromBackend() {//
    return this.http.get('http://localhost:5000/getstuff')
    .map(data=>{
        data.json();
        console.log(data.json());
        return data.json();
    })
  }
}

App.Component.ts

import { Component , OnInit} from '@angular/core';
import { WebService } from './webservices/webservices.services';
import { Http, Response } from '@angular/http';
import { Router } from '@angular/router';
import {HttpModule} from '@angular/http';
import { RouterModule } from '@angular/router';
@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
  providers: [WebService]
})
export class AppComponent implements OnInit {

  constructor(private http: Http,  private webservice: WebService, private router: Router) { }
  title: string = 'My first angular2-google-maps project';
  lat: number = 45.478418;
  lng: number = -122.209007;
  msgBackend: string = "";
  public ngOnInit(){

  }
 public getData(){
    this.webservice.getDataFromBackend()
      .subscribe(
      (data) => this.handleData(data),

      () => console.log('Write to console output')

      );
  }

    private handleData(data: Response) {
    if (data.status === 200) {
      let receivedData = data.json();
      console.log(receivedData);
      this.msgBackend= receivedData;
      return this.msgBackend;
    }


  }





}

So when my app runs, it does hit the Flask app and returns a 200. Also, the console does indeed write "Write to console output". I also tried adding an observable Observable but that didn't work. I think I'm just not grasping Angular2 http and async stuff.

EDIT: console.log(receivedData); why isn't it going to the console?

Swope answered 12/5, 2017 at 0:9 Comment(2)
What's the issue? You never mentioned it.Monjo
console.log(receivedData); Why isn't it going to the console?Swope
N
8

As mentioned, since this is not JSON, but string, use response.text() instead, like so:

public getDataFromBackend() {
  return this.http.get('http://localhost:5000/getstuff')
   .map(response => response.text())
}

and in component:

public getData(){
  this.webservice.getDataFromBackend()
    .subscribe(data => {
       this.handleData(data),
  });
}

And in your handleData, we are no longer dealing with Response, but the data is just simply a string at that point:

private handleData(data: string) {
  console.log(data);
  this.msgBackend= data;
}    
Nutria answered 12/5, 2017 at 6:31 Comment(2)
Getting a `Property 'text' does not exist on type 'Object'Burgwell
For me it worked with the responseType: 'text' (see my answer)Barbiturism
B
5

The answer with the most upvotes did not work for me, sadly the suggested answer from the angular manual required a @ts-ignore but still works fine.

// @ts-ignore
return this.http.get<string>('my-api-url', {responseType: 'text'});

From https://angular.io/guide/http#requesting-a-typed-response :

// this works 
 client.get('/foo', {responseType: 'text'})
Barbiturism answered 17/8, 2021 at 9:12 Comment(1)
Thanks the {responseType: 'text'}) worked for meBulbar
M
0

If you're returning text and not actual json use response.text()

Update your getDataFromBackend to this, returning the text, not the response.

public getDataFromBackend() {
    return this.http.get('http://localhost:5000/getstuff')
    .map(response =>{
        response.json();
        return response.body;
    })
  }

Then update handleData to:

private handleData(data: any) {
    console.log(data);
    this.msgBackend= data;
}
Monjo answered 12/5, 2017 at 0:55 Comment(1)
Hmm...Whatever the Visual Studio Code equivalence of intellisense is doesn't like response.Body.Swope
C
0

I ran into this issue myself. Based on the observed behavior the httpclient is expecting a Json object and not a simple string. I was seeing a parsing error when I returned the simple string.

The solution I used was to wrap the result in the back-end into a Json object

    return this.http.get(url, {headers:header}).pipe(
        map(this.handleGetResponse),
        catchError(this.handleResponseError));

    private handleGetResponse(res: any): string {
    var returnValue: string = res.result;
    return returnValue;
    }
Coadjutor answered 21/10, 2019 at 20:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.