显示来自ngFor的详细信息

时间:2019-02-24 09:27:57

标签: node.js angular mongodb express blogs

我正在使用Angular 7,MongoDB和NodeJS创建一个Blog。到目前为止,我已经创建了一个组件,该组件遍历数据库中的所有帖子并将它们显示在单个页面上。

<div class="container-fluid">
  <div class="row" *ngIf="posts.length > 0" >
    <div class="col-lg-12 col-md-12 col-xl-12 text-center" *ngFor="let post of posts ">
      <div class="post-preview" >
          <h2 class="post-title text-center">
            {{ post.title }}
          </h2>
          <h3 class="post-subtitle text-center">
            {{ post.subtitle }}
          </h3>
          <br>
          <div class="post-image">
            <img [src]="post.imagePath" [alt]="post.title">
          </div>
          <br>
        <p class="post-meta text-center">{{post.date}}</p>
      </div>
      </div> 
    
  </div>
</div>

这是用于在单个页面上显示所有博客文章。当用户单击单个帖子时,应该将他定向到仅显示该帖子的详细信息的页面(例如博客内容)。我该如何实现?

在posts.service中,我具有以下功能以获取单个帖子。

  getPost(id: string) {
    return this.http.get<{_id: string, title: string, subtitle: string, content: string, date: Date, imagePath: string}>(
      'http://localhost:3000/api/posts/' + id);
  }

在后端,我有以下路线:

router.get("/:id", (req, res, next) => {
  Post.findById(req.params.id).then(post => {
    if (post) {
      res.status(200).json(post);
    } else {
      res.status(404).json({
        message: 'Post not found!'
      });
    }
  });
});

1 个答案:

答案 0 :(得分:0)

我在这里找到了答案:https://codecraft.tv/courses/angular/routing/parameterised-routes/

解决方案: [1] 将路由器中的参数化路由指定为:

{ path: 'blog/:postId', component: SinglePostComponent }

[2] 创建一个链接以将用户定向到指定的博客文章

 <a [routerLink]="['/blog', post.id]" > </a>

[3] 在SinglePostComponent.ts中,输入以下代码:

export class SinglePostComponent implements OnInit {
  post: Post;
  private postId: string;


  constructor(
    private route: ActivatedRoute,
    private postsService: PostsService
  ) {}

  ngOnInit() {
    this.route.paramMap.subscribe((paramMap: ParamMap) => {
      this.postId = paramMap.get('postId');
      this.postsService.getPost(this.postId).subscribe(postData => {

        this.post = {id: postData._id, title: postData.title, subtitle: postData.subtitle,
          content: postData.content, date: postData.date, imagePath: postData.imagePath};
      });

    }
    );
}


}