显示ngFor的详细帖子

问题描述 投票:0回答:1

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

<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!'
      });
    }
  });
});
node.js angular mongodb express blogs
1个回答
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};
      });

    }
    );
}


}
© www.soinside.com 2019 - 2024. All rights reserved.