如何使用ngFor - Angular Firebase仅显示特定用户上传的图像

时间:2018-04-23 17:47:00

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

我正在使用 Angular Firebase ,将图片上传到Firebase存储并显示它们。 我试图只显示特定用户上传的图像。但是当我这样做时,会显示Firebase中上传的所有图像(所有用户)。

我应该做出哪些改变?以下是我的代码

Gallerycomponent.ts

import { Component, OnInit, OnChanges } from '@angular/core';
import { ImageService } from '../services/image.service';
import { GalleryImage } from '../models/galleryImage.model';
import { Observable } from 'rxjs/Observable';

@Component({
selector: 'app-gallery',
templateUrl: './gallery.component.html',
styleUrls: ['./gallery.component.css']
})
export class GalleryComponent implements OnInit, OnChanges {
  images: Observable<GalleryImage[]>;

constructor(private imageService: ImageService) { }

 ngOnInit() {
  this.images = this.imageService.getImages();
 }

ngOnChanges() {
  this.images = this.imageService.getImages();
 }
}

gallerycomponent.html

<div class="row">
    <h2>Latest Photos</h2>
    <ul id="thumbnailsList">
        <li *ngFor="let image of images | async" class="img">
            <a [routerLink]="['/image', image.$key]">
            <img src="{{image.url}}" class="tn">
            </a>
        </li>
    </ul>
</div>

image.service.ts (*已从此删除了导入)

@Injectable()
export class ImageService {
  private uid: string;

  constructor(private afAuth: AngularFireAuth, private db: AngularFireDatabase) { 
    this.afAuth.authState.subscribe(auth => {
      if (auth !== undefined && auth !== null) {
        this.uid = auth.uid;
      }
    });
  }

  getImages(): Observable<GalleryImage[]> {
    return this.db.list('uploads');
  }

  getImage(key: string) {
    return firebase.database().ref('uploads/' + key).once('value')
    .then((snap) => snap.val());
  }
}

上传service.ts

@Injectable()
export class UploadService {

  private basePath = '/uploads';
  private uploads: FirebaseListObservable<GalleryImage[]>;

  constructor(private ngFire: AngularFireModule, private db: AngularFireDatabase) { }

  uploadFile(upload: Upload) {
    const storageRef = firebase.storage().ref();
    const uploadTask = storageRef.child(`${this.basePath}/${upload.file.name}`)
      .put(upload.file);

    uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
      // three observers
      // 1.) state_changed observer
      (snapshot) => {
        // upload in progress
        upload.progress = (uploadTask.snapshot.bytesTransferred / uploadTask.snapshot.totalBytes) * 100;
        console.log(upload.progress);
      },
      // 2.) error observer
      (error) => {
        // upload failed
        console.log(error);
      },
      // 3.) success observer
      (): any => {
        upload.url = uploadTask.snapshot.downloadURL;
        upload.name = upload.file.name;
        this.saveFileData(upload);
      }
    );
  }
  private saveFileData(upload: Upload) {
    this.db.list(`${this.basePath}/`).push(upload);
    console.log('File saved!: ' + upload.url);
  }
}

任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

因此,有几种方法可以解决这个问题,但对于初学者来说,您需要将用户存储在数据库的某个方面,以便您可以调用上传的所有图像实例由该用户。我不确定您使用什么来获取用户的个人资料(即应用程序中的事件或输入字段的firebase端),但您还需要将其存储在数据库中。<\ n / p>

为了在您的代码中实现这一点,我建议这样的事情:

// 3.) success observer
  (): any => {
    upload.url = uploadTask.snapshot.downloadURL;
    upload.name = upload.file.name;
    upload.user = upload.[WHATEVER SERVICE YOU'RE STORING THE USER IN].username;
    this.saveFileData(upload);
  }

一旦你有了这个,当你重新调用图像时,你仍然可以像处理它一样抓取图像,但也会在你的循环中添加一个ngIf条件,所以它看起来像: / p>

<强> gallerycomponent.html

<div class="row">
<h2>Latest Photos</h2>
<ul id="thumbnailsList">
    <li *ngFor="let image of images | async" class="img">
      <div *ngIf="image.user == 'username'">
        <a [routerLink]="['/image', image.$key]">
        <img src="{{image.url}}" class="tn">
        </a>
      </div>
    </li>
</ul>

需要注意的一点是,您不能拥有多个structural directive on the same element,,这就是添加额外div的原因。