首页 > 解决方案 > 在页面初始化时获取图像

问题描述

当我输入用户配置文件时,我想从我的 firebase 存储中获取我的图像。

我为自己尝试了一些东西,但这不起作用。

上传.service.ts:

import { Injectable, Inject } from '@angular/core';
import { AngularFireStorage } from '@angular/fire/storage';
import firebase from 'firebase/app';
import { User, NgAuthService } from '../auth/auth.service';

@Injectable({
  providedIn: 'root',
})
export class UploadService {
  file: File;
  url = '';
  constructor(private afStorage: AngularFireStorage, @Inject(NgAuthService) private user: User) { }
  iUser = this.user.uid;
  basePath = `/uploads/images/${this.iUser}`;

  //method to upload file at firebase storage
  async uploadFile(event: any) {
    this.file = event.files[0]
    const filePath = `${this.basePath}/${this.file.name}`;    //path at which image will be stored in the firebase storage
    const snap = await this.afStorage.upload(filePath, this.file);
    if (this.file) {
      this.getUrl(snap);
    } else {
      console.log("Select a image please.")
    }
    this.getUrl(snap);
  }

  //method to retrieve download url
  async getUrl(snap: firebase.storage.UploadTaskSnapshot) {
    await snap.ref.getDownloadURL().then(url => {
      this.url = url;  //store the URL
      console.log(this.url);
    });
  }
}

用户配置文件.component.ts:

import { Component, OnInit } from '@angular/core';
import { UploadService } from '../../storage/upload.service';
import { AngularFireStorage } from '@angular/fire/storage';
import firebase from 'firebase/app';

@Component({
  selector: 'app-user-profile',
  templateUrl: './user-profile.component.html',
  styleUrls: ['./user-profile.component.scss'],
})
export class UserProfileComponent implements OnInit {
  constructor(
    public uploadService: UploadService,
    public afStorage: AngularFireStorage,
    ) { }

    image = this.uploadService.url;

  ngOnInit() {
    this.uploadService.getUrl();
  }
}

不知道我该怎么做。我想使用我的服务文件中的私有方法来执行此操作,但它希望我提供一个我在组件文件中没有的参数。然后我试着打电话给我,我可以尝试为此提供一个 StackBlitz。

链接到 StakBlitz:https ://stackblitz.com/edit/angular-ivy-34jf1q ?

标签: javascriptangularfirebasefirebase-storage

解决方案


在页面加载时获取异步数据的一种好方法是使用Resolvers,它允许您在路由导航完成之前调用 api 调用并检索数据,以便在您到达时所有数据都在那里。

不幸的是,我对 firebase 不够熟悉,不知道如何获取“snap”参数。可能值得研究AngularFire以使事情变得更简单(也许?)祝你好运!


推荐阅读