在Angular 4中休息api调用和响应

时间:2018-02-21 16:06:06

标签: angular rest

我正在尝试在组件中打印REST api调用的响应,但我得到'未定义':

服务:

  getPosts() {
      return this.http.get('http://api.local/posts')
          .map(res=>res.json());
  }

  getMainImage(postId) {
      return this.http.get('http://api.local/image/'+postId)
          .map(res=>res.json());
  }

组件:

  constructor(private blogService:BlogService) {
      this.blogService.getPosts().subscribe((posts) => {
          this.posts = posts; //the response of getPosts() api call is stored correctly in posts property.
      });
  }

  getMainImage(postId) {
    this.blogService.getMainImage(postId).subscribe((img) => {
      console.log(img); // logs the api response correctly
      return img; // returns nothing - calling this method returns undefined.
    });
  }

组件html:

<div class="row" *ngFor="let post of posts"> <!--works fine, all posts are displayed-->
<p>{{post.title}}</p> <!--works fine-->
<img src="{{getMainImage(post.id)}}"> <!--somehow this throws the browser into a infinite page loading or crashes the browser.-->

我要做的是在getMainImage()中返回api调用的响应(目前我正在'未定义')并在组件html中显示该响应,因为api返回响应(页面加载并在响应进入时填充。)

1 个答案:

答案 0 :(得分:0)

您无法在subscribe中返回结果。这就是它应该做的,你不能(不应该)从它返回任何东西。

Documentation for the result of subscribe

  

(Disposable):在指定的调度程序上发生订阅和取消订阅的源序列。

修复

您可以使用async pipe,但仍需要在本地存储observable,以便每次调用该方法时都不会重新创建它。像这样:

cachedImageLookups: any = {};
getMainImage(postId) {
  if(!this.cachedImageLookups[postId])
     this.cachedImageLookups[postId] = this.blogService.getMainImage(postId);
  return this.cachedImageLookups[postId];
}

<img src="{{ (getMainImage(post.id) | async)?.image_url }}">