动态存储文件检索

时间:2017-04-07 22:36:49

标签: firebase angularfire2

我已设法使用此功能检索硬编码图像(从this得到基础):

listings.component.ts

import { Component, OnInit } from '@angular/core';
import {FirebaseService} from '../../services/firebase.service';
import * as firebase from 'firebase';

@Component({
  selector: 'app-listings',
  templateUrl: './listings.component.html',
  styleUrls: ['./listings.component.css']
})
export class ListingsComponent implements OnInit {
  listings:any;
  image:string;

  constructor(private firebaseService:FirebaseService) {
    let image = firebase.storage().ref().child('myFolder/myImage.jpg').getDownloadURL().then((url) => {
        // Set image url
        this.image = url;
      }).catch((error) => {
        console.log(error);
      });
  }

  ngOnInit() {
    this.firebaseService.getListings().subscribe(listings => {
      console.log(listings);
      this.listings = listings;
    });
  }

}

但我无法弄清楚如何使用类似

的动态检索图像
<div *ngFor="let listing of listings">
  <img src="{{'myFolder/' + listing.path + '.jpg'}}" />
</div>

1 个答案:

答案 0 :(得分:0)

I'm wondering if you can join the path to the listings Observable.

So in your service:

getListings(): Obserable<any> {
    let results = this.af.database.list(`path/to/data`)
    // Each time getListings() emits, switch to unsubscribe/ignore
    // any pending member queries:
    .switchMap(listings => {
        // Map the listings to the array of observables that are to be
        // joined. When the observables emit a value, update the listing.
        let joinedObservables: any[] = []
        listings.forEach(listing => {
            // Does the listing contain the string you want to plug into the path? 
            // If so...
            joinedObservables.push(firebase.storage().ref().child(`myFolder/${listing.path}`).getDownloadURL()
            // I'm a little unsure of whether this can be done here.
            .then(url => {
                listing.imagePath = url
            })
            .catch(error => {
                console.log(error)
            })
            )
        })            
        // Join the member observables and use the result selector to
        // return the listings - which will have been updated.
        return Observable.combineLatest(joinedObservables, () => listings)
    })
    return results
}

Component:

ngOnInit() {
    this.listings = this.firebaseService.getListings()
}

Then in your template:

<div *ngFor="let listing of listings | async">
    <img [src]="listing.imagePath">
</div>

I'm guessing this will need some adjusting. Or it may not work at all. If nothing else consider that this might be a task better suited for your service. Remember also that you are going to have to import the operators used; e.g., switchMap (which is imported as flatMap) and combineLatest.