【发布时间】:2018-04-23 17:47:00
【问题描述】:
我正在使用 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);
}
}
任何帮助将不胜感激。谢谢。
【问题讨论】:
-
你看过queries for AngularFire吗?你只需要
db.list('/images', ref => ref.orderByChild('user').equalTo('kato'))这样的东西
标签: angular firebase firebase-realtime-database firebase-authentication