通过文档ID获取数据

时间:2019-07-06 19:48:27

标签: angularfire2

我正在尝试通过ID文档获取数据。 Chrome开发者控制台,但报告未定义。 我不知道为什么以及如何解决它。

我有这些组成部分。后列表,后详细信息,postService和post.ts。

post.ts

export class Post {
    title: string;
    content: string;
    description: string;
    published: Date;
}

post.service.ts

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreDocument, AngularFirestoreCollection } from '@angular/fire/firestore';
import { map } from 'rxjs/operators';

import { Post } from "./post";

@Injectable({
  providedIn: 'root'
})
export class PostService {

  postCollection: AngularFirestoreCollection<Post>;
  postDoc: AngularFirestoreDocument<Post>

  constructor(private db: AngularFirestore) {
    this.postCollection = this.db.collection('Article', ref => ref.orderBy('published', 'desc'))
   }

  getPost(){
    return this.postCollection.snapshotChanges().pipe(
      map(action => action.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.db.doc<Post>(`post/${id}`)
      return this.postDoc.valueChanges()
  }

}

post-list.component.ts

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Post } from '../post';
import { PostService } from '../post.service';

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

  posts: Observable<Post[]>

  constructor(private postService: PostService) { }

  ngOnInit() {
    this.posts = this.postService.getPost()
    console.log(this)
  }

}

post-detail.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router'
import { PostService } from '../post.service';
import { Post } from '../post';


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

  post: Post

  constructor(private route: ActivatedRoute,
              private postService: PostService

              ) 
              { }

  ngOnInit() {
    this.getPost()
    console.log(this.post)
  }

  getPost(){
    const id = this.route.snapshot.paramMap.get('id')
    return this.postService.getPostData(id).subscribe(data => this.post = data)
  }

}

在post-list.component.html中工作正常,我有数据。

<div *ngFor='let post of posts | async'>
  <h3 routerLink="{{post.id}}">{{post.title}}</h3>
  <p>{{post.description}}</p>
</div>

但是在post-detail.component.html中什么也没有。我看到的Chrome开发者控制台:发布:未定义

<div *ngIf="post">
  <h3>{{post.title}}</h3>
  <p>{{post.content}}</p>

</div>

请问有人会发现错误吗?我不知道如何解决它,为什么发布:未定义。

0 个答案:

没有答案