无法从角度http检索数据

时间:2018-01-05 01:57:11

标签: mongodb angular rest mean-stack angular-http

我尝试使用下面的代码使用http模块从我的mongodb中的集合中检索数据,

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

每次都有失败的回复

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)

但是当我和邮递员一起尝试时,我得到了预期的结果, enter image description here

我从服务中返回响应,并从像这样的组件订阅其数据,

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

我做错了什么?任何帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

您需要转换map中的回复并订阅该回复才能获得最终JSON回复

更新的代码看起来像这样 -

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

我希望这会有所帮助。 :)

答案 1 :(得分:0)

尝试在.map()

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

或删除括号(这会给你隐含的回报),

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