将服务响应映射到组件模型以显示在视图上

时间:2018-10-19 15:52:04

标签: angular angular6

我有一个Post API,该API返回以下内容:

{
  "data": [
    {
      "id": 1,
      "title": "Title 1",
      "content": "Lorem ipsum",
      "category": { id = 2, name = "A" }
      "created_at": "2018-10-20 10:14:23"
    },
    {
      "id": 2,
      "title": "Title 2",
      "content": "Lorem ipsum",
      "category": { id = 4, name = "P" }
      "created_at": "2018-12-20 12:17:41"
    }
  ]
}

我有一个帖子列表组件,用于显示最重要的帖子,我使用PostService在其中调用API,该API返回前一个响应:

export class PostListComponent implements OnInit {    

  posts: PostListModel[];

  constructor(private postService: PostService) { }    

  ngOnInit() {

    this.posts = this.postService.getTopPosts()
                     .subscribe(???);
  }    

}

PostListModel如下:

export interface PostListModel {
  id: number;
  title: string;
  content: string;
  categoryName: string;
  hidden: boolean;
}

因此,在我的组件上,我需要将API响应映射到PostListModel [],其中所有具有相同名称的属性都将被复制,categoryName和隐藏属性是:

API Category.Name > PostListModel categoryName
PostListModel hidden = false (for all posts)

Hidden是允许用户在视图上设置一行的属性,例如一个帖子,隐藏起来。因此它与API响应无关。

注意:请注意,这是否是最好的选择...

3 个答案:

答案 0 :(得分:2)

您可以对名称与组件订阅方法中的名称完全匹配的道具使用传播运算符,例如:

this.postService.getTopPosts()
.subscribe((s)=>{
  this.posts = s.data.map((item)=>{
    return {
     ...item,
     categoryName:item.category.name
    }
  }
});

答案 1 :(得分:1)

从API接收数据后,您就可以映射数据

export class PostListComponent implements OnInit {    

  posts: PostListModel[];

  constructor(private postService: PostService) { }    

  ngOnInit() {

    this.posts = this.postService.getTopPosts().map(post=>{id:post.id, title:post.title, content:post.content, categoryName : post.category['name'],  hidden : false}).subscribe(posts=> this.posts);
  }    

}
  

注意:您可以在Service类本身中进行相同的映射。

答案 2 :(得分:1)

我会这样:

模型:

 export class APIResponseItem {
              id: number
              title: string;
              content: string;
              category: { id: number, name: string }
              created_at: Date
    }


export class PostListModel {
  id: number;
  title: string;
  content: string;
  categoryName: string;
  hidden: boolean;

  constructor(data?: APIResponseItem) {
    if(data) {
      this.id = data.id;
      this.title = data.title;
      this.content = data.content;
      this.categoryName = data.category.name;
      this.hidden = false;
    }
  }
}

服务:

this.postService.getTopPosts().subscribe((response: APIResponseItem[]) => {
      this.posts = [];
      response.forEach(item => {
        this.posts.push(new PostListModel(item))
      });
    });