【问题标题】:how to display only the images uploaded by the specific user using ngFor - Angular Firebase如何仅显示特定用户使用 ngFor 上传的图像 - Angular Firebase
【发布时间】:2018-04-23 17:47:00
【问题描述】:

我正在使用 AngularFirebase 将图像上传到 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);
  }
}

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

【问题讨论】:

  • 你看过queries for AngularFire吗?你只需要db.list('/images', ref =&gt; ref.orderByChild('user').equalTo('kato'))这样的东西

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


【解决方案1】:

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

为了在您的代码中实现这一点,我建议如下:

// 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 条件,使其看起来像:

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 的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-12
    • 2017-10-18
    • 2019-06-02
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    相关资源
    最近更新 更多