【问题标题】:Why is my Post List component not loading?为什么我的帖子列表组件没有加载?
【发布时间】:2019-12-30 09:36:29
【问题描述】:

所以正如问题所述,我的帖子模块中有一个组件,即 PostList。它应该做的是在用户访问网站时立即加载。 它的代码如下 posts-list.component.css

section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px,1fr));
  grid-template-rows: auto;
  grid-gap: 10px;
  margin: 0 auto;
  max-width: 90%;
}
mat-card {
  margin: 10px 0;
}

post-list.component.html

<section>
  <mat-card *ngFor="let post of posts | async">
    <mat-card-content routerLink="{{post.id}}">
      <img mat-card-image src="{{post.image}}" alt="{{post.title}}">
      <h2>{{post.title}}</h2>
      <p>
        <small>Posted by {{post.author}} &bull; on {{post.published | date:"fullDate"}}</small>
      </p>
    </mat-card-content>
    <mat-card-actions align="end" *ngIf="auth.currentUserId === post.authorId">
      <button mat-icon-button (click)="delete(post.id)">
        <mat-icon>delete</mat-icon>
      </button>
    </mat-card-actions>
  </mat-card>
</section>

post-list.component.ts

import { Component, OnInit } from '@angular/core'
import { Observable } from 'rxjs/Observable'

import { PostService } from '../posts.service'
import { Post } from '../post'
import { AuthService } from '../../core/auth.service'

@Component({
  selector: 'app-post-list',
  templateUrl: './post-list.component.html',
  styleUrls: ['./post-list.component.css']
})
export class PostListComponent implements OnInit {
  posts: Observable<Post[]>
  constructor(private postService: PostService, public auth: AuthService) {}

  ngOnInit() {
    this.posts = this.postService.getPosts()
  }

  delete(id: string) {
    this.postService.delete(id)
  }

}

由于它在模块内,我已将其路由为在 post.module.ts

中以 /blog 的形式打开
const routes: Routes = [
{path:'blog',component:PostListComponent},
{path:'blog/:id',component:PostDetailComponent},
{path:'dashboard',component:PostDashboardComponent}
]

我不知道为什么它没有显示在网站上。

在 app.module.ts 中

const routes: Routes = [
  { path: '', redirectTo: '/blog', pathMatch: 'full'},
  { path: '', loadChildren: './posts/posts.module#PostsModule' },

]

posts.service.ts

import { Injectable } from '@angular/core'
import {
  AngularFirestore,
  AngularFirestoreCollection,
  AngularFirestoreDocument
} from '@angular/fire/firestore'
import { Post } from './post'
import 'rxjs/add/operator/map'


@Injectable()
export class PostService {
  postsCollection: AngularFirestoreCollection<Post>
  postDoc: AngularFirestoreDocument<Post>

  constructor(private afs: AngularFirestore) {
    this.postsCollection = this.afs.collection('posts', ref =>
      ref.orderBy('published', 'desc')
    )
  }

  getPosts() {
    return this.postsCollection.snapshotChanges().map(actions => {
      return actions.map(a => {
        const data = a.payload.doc.data() as Post
        const id = a.payload.doc.id
        return { id, ...data }
      })
    })
  }

  getPostData(id: string) {
    this.postDoc = this.afs.doc<Post>(`posts/${id}`)
    return this.postDoc.valueChanges()
  }

  getPost(id: string) {
    return this.afs.doc<Post>(`posts/${id}`)
  }

  create(data: Post) {
    this.postsCollection.add(data)
  }

  delete(id: string) {
    return this.getPost(id).delete()
  }

  update(id: string, formData) {
    return this.getPost(id).update(formData)
  }
}

请指导我做错了什么。我就是想不通。

【问题讨论】:

  • 请订阅this.postService.getPosts()邮递服务getPosts()方法
  • 你的路由错误,见angular.io/guide/…
  • sizeposts 是什么?
  • 请发PostService的代码
  • 控制台有错误吗?

标签: javascript angular routing angular-router


【解决方案1】:

我认为你需要以不同的方式加载你的模块 在 app.module.ts

const routes: Routes = [{
  path: 'blog',
  loadChildren: () => import('./modules/posts/posts.module').then(m => m.PostsModule),
},
{ 
  path: '',
  redirectTo: '/blog',
  pathMatch: 'full'
},
{
  path:'dashboard',
  component:PostDashboardComponent
}]

注意:在 Angular 8 及更高版本中,我们使用不同的方式加载模块,您使用的方式:./posts/posts.module#PostsModule 是旧方式,请参阅Angular docs

并将您的 post.module.ts 路由更改为

const routes: Routes = [
  {path:'',component:PostListComponent},
  {path:':id',component:PostDetailComponent}
]

【讨论】:

  • 由于post仪表板组件在post模块内部,无法直接在app.module.ts中路由:(
  • 然后,将该组件添加到 post.module.ts 中,并在 url 中添加“dashboard”作为单独的路径(将其设置为 blog/dashboard)。记得在路径前加上 :id
【解决方案2】:

这样试试

ngOnInit() {
    this.postService.getPosts().subscribe((response: any)=> {
      this.posts = response;
   })
  }

【讨论】:

    【解决方案3】:
    this.postService.getPosts().subscribe((posts) => this.posts = posts);
    

    Observables 是惰性的。请订阅以启动它们。

    【讨论】:

      【解决方案4】:
          Change the 
       { path: '', redirectTo: '/blog', pathMatch: 'full'},
            { path: '', loadChildren: './posts/posts.module#PostsModule' }
          to 
            { path: 'blog', loadChildren: './posts/posts.module#PostsModule' }
      
          You can remove the { path: '', redirectTo: '/blog', pathMatch: 'full'} .
          Assuming the './posts' path is correct.
          When the route matches with /blog it checks in the postmodule routing 
           ,it checks with 
          const routes: Routes = [
          {path:'blog',component:PostListComponent},
          {path:'blog/:id',component:PostDetailComponent},
          {path:'dashboard',component:PostDashboardComponent}
          ]
          and serves the PostListComponent
      

      【讨论】:

      • 您的回答是最有帮助的,但不幸的是,它仍然不起作用。
      • 首先,是正在显示的页面,我的意思是它导航到所需的页面
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-15
      • 2013-06-16
      • 2018-08-15
      • 2013-02-28
      • 1970-01-01
      相关资源
      最近更新 更多