【问题标题】:Displaying a detailed post from ngFor显示来自 ngFor 的详细帖子
【发布时间】:2019-02-24 09:27:56
【问题描述】:

我正在使用 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!'
      });
    }
  });
});

【问题讨论】:

  • 有什么问题?你还没有提到它
  • @ShashankVivek 是的,我做到了。当用户点击单个帖子时,他应该被定向到仅显示该帖子详细信息的页面(如博客内容)。我该如何实现?
  • 尝试在TS 为帖子创建console.log 显示什么?
  • @AldinMuratovic 你试过angular.io/api/router/RouterLink 吗?你有[routerLink]

标签: node.js angular mongodb express blogs


【解决方案1】:

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

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

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

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

 &lt;a [routerLink]="['/blog', post.id]" &gt; &lt;/a&gt;

[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};
      });

    }
    );
}


}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 2022-06-20
    • 2015-05-20
    • 1970-01-01
    相关资源
    最近更新 更多