我离开并返回组件时,snapshotChanges()不显示数据

时间:2018-03-29 00:33:37

标签: javascript firebase angular5 google-cloud-firestore angularfire2

我有一个问题是从firestore接收数据,或者说我得到了数据,问题是当我离开页面时,当我返回页面时,数据不再显示。

奇怪的是我在另一个组件中使用相同的方法并且它可以正常工作,但是在这种形式的组件中会发生这种情况,你们可以帮助我吗?

component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';

import { ModuleService } from '../modulo.service';

import { Module } from '../modulo.model';
import { element } from 'protractor';


import { ToastrService } from 'ngx-toastr';
import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'cma-modulo-cadastro',
  templateUrl: './modulo-cadastro.component.html'
})

export class ModuloCadastroComponent implements OnInit {
  $key;

  moduleItens: Module[];
  moduleSelected: Module = new Module();

  selectedFiles: FileList;
  file: File;

  @ViewChild('myImage')
  myInputVariable: any;

  constructor(private moduleService: ModuleService,
              private toastr: ToastrService,
              private route: ActivatedRoute) {}

  ngOnInit() {

    // Reseta o formulario
    this.resetForm();

    // Recupera a key do modulo pela url
    this.route.params.subscribe((res: any) => {
      this.$key = res.$key;
    });

    // Armazenando os modulos retornados do db
    this.moduleService.getData().subscribe(itens => {
      this.moduleItens = itens;
    });

    if (this.$key) {
      const data = this.moduleService.getModule(this.$key);
      data.then(datas => {
        this.onEdit(datas as Module, this.$key);
      });
    }

  }

  // Recupera a imagem do formulario e salva em file
  chooseFiles(event) {
    this.selectedFiles = event.target.files;
    this.file = this.selectedFiles.item(0);
  }

  // Envio de formulario se tiver key cadastra senao atualiza
  onSubmit(moduleForm: NgForm) {
    if (moduleForm.value.$key == null) {
      this.moduleService.insert(moduleForm.value,  this.file);
    } else {
      this.moduleService.update(moduleForm.value, this.file);
    }
    this.resetForm(moduleForm); // Resetando o formulario
    this.toastr.success('Modulo cadastrado com sucesso!');
  }

  // Enviando os dados para o formulario
  onEdit(module: Module, $key?: string) {
    if ($key) {
      module.$key = $key;
    }
    this.moduleSelected = Object.assign({}, module);
  }

  // Deletando o modulo passado
  onDelete(key: string, image: string) {
    if (confirm('Você deseja deletar o Modulo?') === true) {
      this.moduleService.delete(key, image);
      this.toastr.warning('Deletado com Sucesso!');
    }
  }

  // Metodo que reseta os dados do form
  resetForm(moduleForm?: NgForm) {
    if (moduleForm != null) {
        moduleForm.reset();
    }
    this.myInputVariable.nativeElement.value = null;
    this.file = null;
    this.moduleSelected = {
      $key: null,
      name: '',
      description: '',
      image: null,
      premium: false,
      online: false,
      visits: 0,
      createdAt: null,
    };
  }

  onChange() { }

}

component.html

<div class="content-wrapper">
        <section class="content-header">
            <h1>Modulo
              <small>Cadastro</small>
            </h1>
            <ol class="breadcrumb">
              <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
              <li class="active">Cadastrar-Modulo</li>
            </ol>
          </section>
          <section class="content">
              <div class="row">
                  <div class="col-sm-8">
                        <div class="form-content bg-dark">
                            <form #moduleForm="ngForm" (ngSubmit)="onSubmit(moduleForm)">
                                <input type="hidden" name="$key" #$key="ngModel" [(ngModel)]="moduleSelected.$key">
                                <input type="hidden" name="image" #image="ngModel" [(ngModel)]="moduleSelected.image">
                                <input type="hidden" name="createdAt" #createdAt="ngModel" [(ngModel)]="moduleSelected.createdAt">
                                <input type="hidden" name="visits" #visits="ngModel" [(ngModel)]="moduleSelected.visits">

                                <div class="form-group">
                                    <label for="Name">Nome do Modulo:</label>
                                    <input type="text" class="form-control" name="name" #name="ngModel" [(ngModel)]="moduleSelected.name" placeholder="Digite o nome do Modulo" required>
                                </div>                                 

                                <div class="form-group">
                                    <label for="Image">Imagem do Modulo:</label>
                                    <input type="file" class="form-control-file" #myImage (change)="chooseFiles($event)">
                                </div>

                                <div class="form-group">
                                    <label for="Description">Descrição do Modulo:</label>
                                    <textarea class="form-control" rows="5" name="description" #description="ngModel" [(ngModel)]="moduleSelected.description" placeholder="Digite a Descrição do Modulo" required></textarea>
                                </div>

                                <div class="checkbox">
                                    <label><input type="checkbox" name="premium" #premium="ngModel" [(ngModel)]="moduleSelected.premium" (ngModelChange)="onChange(moduleSelected.premium)"> Premium</label>
                                </div>

                                <div class="checkbox">
                                    <label><input type="checkbox" name="online" #online="ngModel" [(ngModel)]="moduleSelected.online" (ngModelChange)="onChange(moduleSelected.online)"> Online</label>
                                </div>

                                <button type="submit" class="btn btn-default" [disabled]="!moduleForm.valid">
                                    <i class="fa fa-floppy-o"></i> Submit
                                </button>

                                <button type="button" class="btn btn-default" (click)="resetForm(moduleForm)">
                                    <i class="fa fa-repeat"></i> Reset
                                </button>
                            </form>
                        </div>
                  </div>
                  <div class="col-sm-4">

                    <div class="form-content bg-dark">
                        <h4>Modulos</h4>
                        <table class="table table-sm table-hover">
                            <tr *ngFor="let module of moduleItens">
                                <td>{{module.name}}</td>
                                <td style="text-align:right;">
                                    <a class="btn" (click)="onEdit(module)"><i class="fa fa-pencil-square-o"></i></a>
                                    <a class="btn" (click)="onDelete(module.$key, module.image)"><i class="fa fa-trash-o"></i></a>
                                </td>
                            </tr>
                        </table>
                    </div>
                  </div>
              </div>
          </section>
    </div>

service.ts

import { Injectable } from '@angular/core';
import { Module } from './modulo.model';

import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
import { AngularFireStorage, AngularFireStorageReference, AngularFireUploadTask } from 'angularfire2/storage';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import * as firebase from 'firebase';

import { Observable } from 'rxjs/Observable';
import { ToastrService } from 'ngx-toastr';


@Injectable()
export class ModuleService {

    // Angular Storage/Upload
    ref: AngularFireStorageReference;
    task: AngularFireUploadTask;

    // Angular firestore
    moduleCollectionRef: AngularFirestoreCollection<Module>;
    moduleItens: Observable<Module[]>;

    moduleDoc: AngularFirestoreDocument<Module>;
    singleModule: Observable<Module>;

    constructor( private afDatabase: AngularFireDatabase,
        private afStorage: AngularFireStorage,
        private aFirestore: AngularFirestore,
        private toastr: ToastrService) {

        this.moduleCollectionRef = this.aFirestore.collection<Module>('modulos/');
        this.moduleItens = this.moduleCollectionRef.snapshotChanges().map(actions => {
            return actions.map(action => {
                const data = action.payload.doc.data() as Module;
                const $key = action.payload.doc.id;
                return {$key, ...data};
            });
        });
    }

    getData() {
        return this.moduleItens;
    }

    getModule($id) {
        var db = firebase.firestore();
        var documentReference = db.collection('modulos/').doc($id);
        return documentReference.get().then(function(documentSnapshot) {
            const data = documentSnapshot.data();
            return data;
        });
    }

    insert (module: Module, file: File) {
        let result: boolean;
        const storageRef = firebase.storage().ref();
        let uniqkey = 'img-' + Math.floor(Math.random() * 1000000);
        const uploadTask = storageRef.child('/module_pictures/' + uniqkey).put(file);

        uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
            (snapshot) => {
            // in progress
            },
            (error) => {
            // fail
            console.log(error);
            },
            () => {
                module.image = uniqkey;
                module.visits = 0;
                module.createdAt = new Date().toLocaleDateString('pt-br').toString();
                this.moduleCollectionRef.add({
                    name: module.name,
                    description: module.description,
                    premium: module.premium,
                    online: module.online,
                    image: module.image,
                    visits: module.visits,
                    createdAt: module.createdAt
                })
                .then(function (docRef) {
                    console.log('Document written with ID: ', docRef.id);
                })
                .catch(function(error) {
                    console.error('Error adding document: ', error);
                });
            }
        );
    }

    update (module: Module, file: File) {
        if (file != null) {
            const storageRef = firebase.storage().ref();
            storageRef.child('/module_pictures/' + module.image).delete();

            let uniqkey = 'img-' + Math.floor(Math.random() * 1000000);
            const uploadTask = storageRef.child('/module_pictures/' + uniqkey).put(file);

            uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
                (snapshot) => {
                // in progress
                },
                (error) => {
                // fail
                console.log(error);
                },
                () => {
                // success
                module.image = uniqkey;
                if (module.visits == null) { module.visits = 0; }
                if (module.premium == null) { module.premium = false; }
                if (module.online == null) { module.online = false; }
                this.moduleCollectionRef.doc(module.$key).update({
                    name: module.name,
                    description: module.description,
                    premium: module.premium,
                    online: module.online,
                    image: module.image,
                    visits: module.visits,
                    createdAt: module.createdAt
                });
            });
        } else {
            if (module.visits == null) { module.visits = 0; }
            if (module.premium == null) { module.premium = false; }
            if (module.online == null) { module.online = false; }
            this.moduleCollectionRef.doc(module.$key).update({
                name: module.name,
                description: module.description,
                premium: module.premium,
                online: module.online,
                image: module.image,
                visits: module.visits,
                createdAt: module.createdAt
            });
        }
    }

    delete ($key: string, image: string) {
        this.moduleCollectionRef.doc($key).delete();
        const storageRef = firebase.storage().ref();
        storageRef.child('/module_pictures/' + image).delete();
    }

}

0 个答案:

没有答案