首页 > 解决方案 > 如何在 Angular 应用程序的单独页面中显示帖子标题?

问题描述

我已经根据他的索引为每个帖子准备了路由。

您可以在屏幕截图 #2 中看到 URL 是动态的。我需要在打开的页面上显示所选帖子的标题

这是存储库的链接https://github.com/paslavskyi9roman/Freecher

<div
  class="post"
  *ngFor="let post of posts; let i = index"
  [attr.data-index]="i"
>
  <a [title]="post.title" [routerLink]="['/post/', i]">
    <div class="title">
      <h1>{{ post.title }}</h1>
      <span>Posted by: {{ post.author }}</span>
    </div>
    <div class="body">
      <p>{{ post.text }}</p>
    </div>
  </a>
</div>

这是我的申请主页

这是所选帖子的页面。

标签: angular

解决方案


首先在您的 Post 界面中添加 id:

export interface Post {
    id: number,
    title: string,
    text: string,
    author: string,
}

然后在你的 mock-post.ts 中添加 id:

export const POSTS: Post[] = [
    {id:1, title: 'Post 1', text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. ', author: 'Nickname'},
    ...
    ...
    ...
    {id:8, title: 'Post21', text: 'lorem 3 text', author: 'Nickname'},
]

像这样更改您的 post.component.html:

<div  class="post"  *ngFor="let post of posts;" [attr.data-index]="post.id">
<a [title]="post.title" [routerLink]="['/post/', post.id]">
<div class="title">
  <h1>{{ post.title }}</h1>
  <span>Posted by: {{ post.author }}</span>
</div>
<div class="body">
  <p>{{ post.text }}</p>
</div>

然后像这样更改您的 view-post.component.ts :

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { POSTS } from 'src/app/mock-posts';
import { Post } from 'src/app/interface-post';   

@Component({
  selector: 'app-view-post',
  templateUrl: './view-post.component.html',
  styleUrls: ['./view-post.component.scss']
})
export class ViewPostComponent implements OnInit {

  id: any;
  post: any;

  constructor(private activatedRoute: ActivatedRoute) {
    this.activatedRoute.paramMap.subscribe((x: { get: (arg0: string) => any; }) => {
      this.id = x.get('id');
    });
  }

  ngOnInit(): void {
    this.post = POSTS.find(x=>x.id == this.id);
  }

}

最后将其添加到您的 view-post.component.html 中:

<div class="view-post">
  <h1>{{post.title}}</h1>
  <p>{{ post.text }}</p>
</div>

推荐阅读