cannot retrieve data from angular http

2019-03-04 03:33发布

I'm trying to retrieve data from a collection in my mongodb using http module using the code below,

getPosts() {
    return this.http.get('http://localhost:5005/blog/getposts').map(res => {
      console.log("mapped result",res);
      res.json()
    });
  }

It fails everytime with a response

Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at Response.webpackJsonp.../../../http/@angular/http.es5.js.Body.json (http.es5.js:797)
    at MapSubscriber.project (auth.service.ts:45)
    at MapSubscriber.webpackJsonp.../../../../rxjs/operators/map.js.MapSubscriber._next (map.js:79)
    at MapSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.next (Subscriber.js:89)
    at XMLHttpRequest.onLoad (http.es5.js:1226)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.es5.js:3881)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424)
    at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (zone.js:192)

but when I try it with postman, I'm getting the expected result which is this, enter image description here

I'm returning the response from the service and subscribing its data from a component like this,

ngOnInit() {
    this.auth.getPosts().subscribe(data => {
      this.value = data.posts;
      console.log("blog component",this.value)
    },err => {
      console.log(err);
    })
  }

What am I doing wrong? Any help would be much appreciated

2条回答
啃猪蹄的小仙女
2楼-- · 2019-03-04 04:04

You need to convert the response in map and subscribe to it to get the final JSON response

Updated code would look like this-

getPosts() {
    return this.http.get('http://localhost:5005/blog/getposts')
    .map(res => res.json())
    .subscribe((data: any) => {
        //console.log(data);
    });
}

I hope this helps. :)

查看更多
地球回转人心会变
3楼-- · 2019-03-04 04:08

Try returning inside the .map()

getPosts() {
    return this.http.get('http://localhost:5005/blog/getposts').map(res => {
      console.log("mapped result",res);
      return res.json()
    });
  }
}

or drop the brackets (this gives you an implied return),

getPosts() {
    return this.http.get('http://localhost:5005/blog/getposts')
      .map(res => res.json() );
  }
}
查看更多
登录 后发表回答