【问题标题】:Angular 2 firebase can't get image from databaseAngular 2 firebase 无法从数据库中获取图像
【发布时间】:2018-03-20 12:30:19
【问题描述】:

我已使用该功能将 img URL 上传到我的数据库:

  private saveFileData(upload: Upload): void {
    this.firebaseAuth.authState.subscribe(auth => {
    this.db.list(`uploads/${auth && auth.email && auth.uid}`).push(upload);
    })
  }

之后我想用那个函数来获取它,第一个是路径引用,因为我只希望登录的用户会看到他们自己上传的内容

this.firebaseAuth.authState.subscribe(auth => {
  if(auth && auth.email && auth.uid) {
this.uploadRef = this.db.list<any>(`uploads/${auth && auth.email && auth.uid}`);
    console.log("Gaunami profilio duomenys")
  }
  else {
    console.log("Nerandama img")
  }

})

最后我想获得上传的图片列表

get getListUploads(): Observable<AngularFireAction<DatabaseSnapshot>[]> {
    return this.uploadRef.snapshotChanges().map(changes => {
      return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
    });
  }

我在控制台中遇到错误:

ERROR TypeError: Cannot read property 'snapshotChanges' of undefined
    at UploadService.get [as getListUploads] (upload.service.ts:30)

上传工作正常,我在我的数据库中看到照片名称和网址,我在存储中看到照片,但无法从那里获取。有什么建议吗?

【问题讨论】:

  • 你的 getListUploads getter 在哪里使用?您能否将 upload.service.ts 添加到您的问题中?

标签: angular typescript firebase firebase-realtime-database firebase-authentication


【解决方案1】:

您对该文件的引用不正确。您正在使用条件来保存它:

auth && auth.email && auth.uid

看看当你在 JS 中使用它时它返回了什么:

console.log({auth: true} &amp;&amp; 'foo.bar@gmail.com' &amp;&amp; 207894193784);

这意味着当您保存帖子时,其名称中仅使用 ID。

现在让我们在不满足条件的条件之一的情况下进行测试:

console.log({auth: true} &amp;&amp; '' &amp;&amp; 207894193784);

如您所见,如果未提供邮件,您将无法获得任何姓名。

您必须重写对该文件的引用,这应该可以解决您的问题。

EDIT建议,服务示例

import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { AngularFireStorage } from 'angularfire2/storage';

@Injectable()
export class StorageService {

  constructor(
    private afsStorage: AngularFireStorage
  ) { }

  createFile(file: File, folder = 'unclassified'): Observable<string> {
    const path = `${Date.now()}-${Math.random().toString(36).slice(-8)}.${file.name.split('.').splice(-1)}`;
    return this.afsStorage.upload(`${folder}/${path.toLowerCase()}`, file).downloadURL();
  }

  removeFile(url: string): Observable<any> {
    const ref = this.afsStorage.storage.refFromURL(url);
    return Observable.fromPromise(ref.delete());
  }
}

第一种方法允许你创建一个文件,并返回一个 url。获取 url 后,您可以在数据库中创建一个文档来存储它。

【讨论】:

  • 还是不明白,如果我只留下 auth.uid 它会给我同样的错误,如果我只留下 auth ,还是一样。
  • 您是否在您的 firebase 中保存了新文件?您要获取的文件的参考是什么?
  • 是的,我理解你所说的,但这并没有真正帮助我理解那个错误发生了什么。
  • 是的,我保存了,它是 Profile/UID/Upload/Filehere
  • 不,我的意思是,我需要一个 URL :) 不是完整的,只是域名后面的内容。
猜你喜欢
  • 1970-01-01
  • 2020-09-26
  • 2021-10-25
  • 2019-06-09
  • 2019-03-03
  • 1970-01-01
  • 2019-05-10
  • 1970-01-01
  • 2021-04-28
相关资源
最近更新 更多