错误TS2339:类型“ {}”上不存在属性“ contenido”

时间:2018-08-15 02:26:56

标签: typescript firebase google-cloud-firestore angular6

我正在用一个6号角和一个Firebase在其Firestore数据库中执行任务,我正在通过表单编辑一些数据,应用程序应该可以工作,但是编译器却给我这个错误:

ERROR in src/app/Components/Posts/dashboard-posts/dashboard-posts.component.ts(113,37): error TS2339: Property 'titulo' does not exist on type '{}'.
src/app/Components/Posts/dashboard-posts/dashboard-posts.component.ts(114,40): error TS2339: Property 'contenido' does not exist on type '{}'.
src/app/Components/Posts/dashboard-posts/dashboard-posts.component.ts(115,39): error TS2339: Property 'estracto' does not exist on type '{}'.
src/app/Components/Posts/dashboard-posts/dashboard-posts.component.ts(116,40): error TS2339: Property 'url_image' does not exist on type '{}'.

我有一个服务和一个正在处理的组件,那么我将把它们都留给他们

服务:

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs';


@Injectable({
  providedIn: 'root'
})
export class FirestoreService {
  // Posts
  constructor(
    private firestore: AngularFirestore
  ) { }
  //Crea un nuevo post
  public createPost(data: { titulo: string, contenido: string, estracto: string, url_image: string }) {
    return this.firestore.collection('posts').add(data);
  }

  //Obtiene un post
  public getPost(documentId: string) {
    return this.firestore.collection('posts').doc(documentId).snapshotChanges();
  }

  //Obtiene todos los posts
  public getPosts() {
    return this.firestore.collection('posts').snapshotChanges();
  }

  //Actualiza un post
  public updatePost(documentId: string, data: { titulo?: string, contenido?: string, estracto?: string, url_image?: string }) {

    return this.firestore.collection('posts').doc(documentId).set(data);
  }

  //Borra un post
  public deletePost(documentId: string) {
    return this.firestore.collection('posts').doc(documentId).delete();
  }
}

这里是组件:

import { Component, OnInit } from '@angular/core';
import { FirestoreService } from '../../../Service/firestore.service';
import { Form, FormControl, FormGroup, Validators } from '@angular/forms';
import { AngularFirestoreCollection } from 'angularfire2/firestore';
import { Observable } from 'rxjs';
import swal from 'sweetalert';

export interface Post {

  id: string;
  titulo: string;
  contenido: string;
  estracto: string;
  url_image: string;

}

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

  public posts = [];
  public currentStatus = 1;
  public newPostForm = new FormGroup({
    titulo: new FormControl('', Validators.required),
    contenido: new FormControl('', Validators.required),
    estracto: new FormControl('', Validators.required),
    url_image: new FormControl('', Validators.required),
    id: new FormControl('')
  });


  constructor(
    private firestoreService: FirestoreService
  ) {
    this.newPostForm.setValue({
      id: '',
      titulo: '',
      contenido: '',
      estracto: '',
      url_image: ''
    });
  }

  postsCollections: AngularFirestoreCollection<Post>;
  postsObservable: Observable<Post[]>;

  ngOnInit() {
    this.firestoreService.getPosts().subscribe((postsSnapshot) => {
      this.posts = [];
      postsSnapshot.forEach((postData: any) => {
        this.posts.push({
          id: postData.payload.doc.id,
          data: postData.payload.doc.data()
        });
      })
    });
  }

  public newPost(form, documentId = null) {
    if (this.currentStatus == 1) {
      let data = {
        titulo: form.titulo,
        contenido: form.contenido,
        estracto: form.estracto,
        url_image: form.url_image
      }
      this.firestoreService.createPost(data).then(() => {
        swal("Listo!", "Tu post ha sido creado extitosamente!", "success");
        this.newPostForm.setValue({
          titulo: '',
          contenido: '',
          estracto: '',
          url_image: '',
          id: ''
        });
      }, (error) => {
        console.error(error);
      });
    } else {
      let data = {
        titulo: form.titulo,
        contenido: form.contenido,
        estracto: form.estracto,
        url_image: form.url_image
      }
      this.firestoreService.updatePost(form.id, form).then(() => {
        this.currentStatus = 1;
        this.newPostForm.setValue({
          titulo: '',
          contenido: '',
          estracto: '',
          url_image: '',
          id: ''
        });
        console.log('Documento editado exitósamente');
      }, (error) => {
        console.log(error);
      });
    }
  }

  public editPost(documentId) {
    this.firestoreService.getPost(documentId).subscribe((post) => {
      this.currentStatus = 2;

      this.newPostForm.setValue({

        id: documentId,
        titulo: post.payload.data().titulo, //Aqui me da el error
        contenido: post.payload.data().contenido, //Aqui me da el error
        estracto: post.payload.data().estracto, //Aqui me da el error
        url_image: post.payload.data().url_image //Aqui me da el error
      });
    });
  }



  public deletePost(documentId) {
    this.firestoreService.deletePost(documentId).then(() => {
      console.log('Documento eliminado!');
    }, (error) => {
      console.error(error);
    });
  }
}

希望你能帮助我。

1 个答案:

答案 0 :(得分:1)

您必须指定文档的类型,否则TypeScript默认为空类型{}。将以下内容添加到服务中(根据需要更改):

export interface Post {
    titulo: string;
    contenido: string;
    estracto: string;
    url_image: string;
}

,然后如下更改getPost

  //Obtiene un post
  public getPost(documentId: string) {
    return this.firestore.collection('posts').doc<Post>(documentId).snapshotChanges();
    //                                           ^^^^^^
  }