cannot retrieve data from angular http

好久不见. 提交于 2019-12-02 18:22:37

问题


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,

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


回答1:


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. :)




回答2:


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() );
  }
}


来源:https://stackoverflow.com/questions/48106186/cannot-retrieve-data-from-angular-http

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!