类型'FileUpload [] []'不能分配给'AngularFireList <fileupload []>'

时间:2018-02-11 13:46:21

标签: angular typescript firebase file-upload firebase-realtime-database

我正在使用Firebase构建一个Angular应用程序,以将图像上传到数据库并从那里检索它。

上载file.service.ts

import {Injectable} from '@angular/core';
import {AngularFireDatabase, AngularFireList} from 'angularfire2/database';
import * as firebase from 'firebase';

import {FileUpload} from '../uploadingpage/fileupload';

@Injectable()
export class UploadFileService {

  constructor(private db: AngularFireDatabase) {}
  getFileUploads (): AngularFireList<FileUpload[]>{
        return this.db.list('/uploads');
    }

  private basePath = '/uploads';
  fileUploads: AngularFireList<FileUpload[]>;

  pushFileToStorage(fileUpload: FileUpload, progress: {percentage: number}) {
    const storageRef = firebase.storage().ref();
    const uploadTask = storageRef.child(`${this.basePath}/${fileUpload.file.name}`).put(fileUpload.file);

    uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
      (snapshot) => {
        // in progress
        const snap = snapshot as firebase.storage.UploadTaskSnapshot
        progress.percentage = Math.round((snap.bytesTransferred / snap.totalBytes) * 100)
      },
      (error) => {
        // fail
        console.log(error)
      },
      () => {
        // success
        fileUpload.url = uploadTask.snapshot.downloadURL
        fileUpload.name = fileUpload.file.name
        this.saveFileData(fileUpload)
      }
    );
  }

  private saveFileData(fileUpload: FileUpload) {
    this.db.list(`${this.basePath}/`).push(fileUpload);
  }
}

uploadingpage.component.ts

import { Component, OnInit } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFireDatabase, AngularFireObject } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
import * as firebase from 'firebase';
import { FirebaseAuthService } from '../auth/firebase-auth.service';

import { ItemService } from '../services/item.service';
import { UploadFileService } from '../services/upload-file.service';
import { FileUpload } from './fileupload';

@Component({
  selector: 'app-uploadingpage',
  templateUrl: './uploadingpage.component.html',
  styleUrls: ['./uploadingpage.component.css']
})
export class ProfileComponent implements OnInit {

  //for image
  selectedFiles: FileList;
  currentFileUpload: FileUpload;
  progress: {percentage: number} = {percentage: 0};


  constructor(
    private afDb: AngularFireDatabase,
    private _auth: FirebaseAuthService,
    private itemService: ItemService,
    private uploadService: UploadFileService 
  ) { }

  ngOnInit() {
  }

  //for image
  selectFile(event) {
    this.selectedFiles = event.target.files;
  }
 //for image
  upload() {
    const file = this.selectedFiles.item(0)
    this.currentFileUpload = new FileUpload(file);
    this.uploadService.pushFileToStorage(this.currentFileUpload, this.progress);
  }

  signOut(){
    this._auth.signOut();
    window.location.href = "";    
  }
}

displaypage.component.ts

import { Component, OnInit } from '@angular/core';
      //additional imports
      import { ItemService } from '../services/item.service';
      import {FileUpload} from '../uploadingpage/fileupload';
      import {UploadFileService} from '../services/upload-file.service';
      import { AngularFireDatabase, AngularFireList } from 'angularfire2/database'; 
      import * as firebase from 'firebase';

      @Component({
        selector: 'app-admin',
        templateUrl: './displaypage.component.html',
        styleUrls: ['./displaypage.component.css']
      })
      export class DisplaypageComponent implements OnInit {

        fileUploads: AngularFireList<FileUpload[]>;

        constructor(private itemService: ItemService, private uploadService: UploadFileService) { }

        ngOnInit() {
          this.itemService.getItems().subscribe(items => {
            this.items = items;
          });
         this.uploadService.getFileUploads().valueChanges().subscribe(result=>{
             this.fileUploads = result;
         });
        }

      }

现在,虽然我可以上传图像并从数据库中检索它,但我的终端显示仍然出现错误 Type 'FileUpload[][]' is not assignable to type 'AngularFireList<FileUpload[]> Property 'query' is missing in type 'FileUpload[][]'.

有关为何发生这种情况的任何想法?

任何形式的帮助将不胜感激。感谢。

1 个答案:

答案 0 :(得分:1)

此处不需要使用AngularFireList类型,

创建一个类

export class Upload {

  $key: string;
  name: string;
  url: string;
  file: File;
  progress:number;
  timestamp: Date = new Date();

  constructor(file: File) {
    this.file = file;
  }
}

并在您的服务中

  uploads: Observable<Upload[]>;

  getUploads() {
    this.uploads = this.db.list(this.basePath).snapshotChanges().map((actions) => {
      return actions.map((a) => {
        const data = a.payload.val();
        const $key = a.payload.key;
        return { $key, ...data };
      });
    });
    return this.uploads;
  }

并在您的组件中

uploads: Observable<Upload[]>;
ngOnInit() {
    this.uploads = this.uploadService.getUploads();   
  }

并使用| async

更改您的div
<div *ngIf="uploads | async; let uploads; else loading"> 
<div *ngFor="let upload of uploads"> 
<img [src]="file.url" id="image" /> 
</div> 
</div>