3

Hi In my Angular Component, i have this code in one of my methods

this.http.get("http://localhost:8080/poeples")
.map(
    resp => { resp = resp.json(); }
).subscribe(
    (data) => { this.poeples = data; },
    err =>  console.log(err)
);

In network tab in chrome dev inspector i saw that my get call returning result, but data is undefined.

Why?

Zze
  • 18,229
  • 13
  • 85
  • 118
shmoolki
  • 1,551
  • 8
  • 34
  • 57

3 Answers3

4

The reason it was not working originally, is because you had this:

resp => { resp = resp.json(); }

You are not returning a value. When you use the curly braces, you have to explicitly define a return value. All you had to do was:

resp => { return resp.json(); }

Or remove the braces:

resp => resp.json() 
Zze
  • 18,229
  • 13
  • 85
  • 118
1

// Your code that isn't working:
/*this.http.get("http://localhost:8080/poeples")
  .map(
    resp => {    
       resp = resp.json()     
    }
  ).subscribe(
      (data) => {
      this.poeples = data;


    },
     err =>  console.log(err)) ;*/
     
// Working code:
@import { map } from 'rxjs/operators';

this.http.get('http://localhost:8080/poeples')
  .pipe(
    // In your example, you are creating a new function with the {} wrapped around this line, but you aren't returning anything, so the return value of the "data" below becomes "undefined."
    map((response) => response.json())
  )
  .subscribe(
    (data) => {
      this.poeples = data;
    },
    (err) => console.log(err)
  );
th3n3wguy
  • 3,649
  • 2
  • 23
  • 30
  • Can you Explain me what was the problem in my code, please? – shmoolki Mar 12 '18 at 22:45
  • 1
    @shmoolki => If you look at the comment just under the `.pipe()` method, it explains the issue with your code. The only reason I posted a slight modification is that the `.map()` method you are using in your question is deprecated in RxJS 5+. – th3n3wguy Mar 12 '18 at 22:47
0

Error - when subscribing request success code not working. This is my code I'm working on

this.userService.addDeliverDetails(form.value) .subscribe( res=>{ this.have=true; }, error=>{ console.log('error') } );

Try to console.log() in error and if it logged that's mean your data coming from the server as text not JSON formatted.

Two solutions 1) change angular to accept text responses 2) change server response to json not to string (plain text)