Angular TypeError:无法读取未定义的属性“名称”

时间:2021-05-28 06:09:11

标签: javascript angular typescript firebase firebase-storage

我想做的是将两种方法分开。但这给我带来了一个问题。因为我试图让一个函数在组件 init 上运行。我想在上传文件时获取文件名并将数据从 uploadFile 传递到 getUrl event.files[0]

我一直试图用我在顶部的其他人声明一个值,但不能,因为我得到“在初始化之前使用了属性‘文件’。”当我尝试这样做时出错。

上传服务:

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 {
  constructor(private afStorage: AngularFireStorage, @Inject(NgAuthService) private user: User) { }
  file: File;
  url = '';
  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
    await this.afStorage.upload(filePath, this.file);
    if (this.file) {
      this.getUrl();
    } else {
      console.log("Select a image please.")
    }
  }

  //method to retrieve download url
  async getUrl() {
    const filePath = `${this.basePath}/${this.file.name}`; // error is coming from here.
    const snap = this.afStorage.storage.ref(filePath);
    await snap.getDownloadURL().then(url => {
      this.url = url;  //store the URL
      console.log(this.url);
    });
  }
}

user-profile.component.ts:

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

@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();
  }
}

堆栈跟踪错误:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'name' of undefined
TypeError: Cannot read property 'name' of undefined
    at UploadService.<anonymous> (upload.service.ts:30)
    at Generator.next (<anonymous>)
    at tslib.es6.js:76
    at new ZoneAwarePromise (zone.js:1387)
    at __awaiter (tslib.es6.js:72)
    at UploadService.getUrl (upload.service.ts:29)
    at UserProfileComponent.ngOnInit (user-profile.component.ts:19)
    at callHook (core.js:2526)
    at callHooks (core.js:2495)
    at executeInitAndCheckHooks (core.js:2446)
    at resolvePromise (zone.js:1213)
    at new ZoneAwarePromise (zone.js:1390)
    at __awaiter (tslib.es6.js:72)
    at UploadService.getUrl (upload.service.ts:29)
    at UserProfileComponent.ngOnInit (user-profile.component.ts:19)
    at callHook (core.js:2526)
    at callHooks (core.js:2495)
    at executeInitAndCheckHooks (core.js:2446)
    at refreshView (core.js:9456)
    at refreshEmbeddedViews (core.js:10566)

如果需要,我可以提供更多信息或任何东西。

1 个答案:

答案 0 :(得分:0)

似乎方法 getUrl() 期望 this.file.name 在调用时被定义。

一个简单的解决方法是仅在您知道 getUrl() 上的 name 属性具有值时才调用 this.file,例如

if ( this.file && this.file.name ) {
  this.getUrl();
} else {
  console.log("Select a image please.")
}

或更简单的使用空检查

if ( this.file?.name ) {
  this.getUrl();
} else {
  console.log("Select a image please.")
}

或者,您可能希望调用 getUrl(),而不管您是否确实在 this.file = event.files[0]; 行中返回了一个文件。在这种情况下,您需要保证 this.file.name 不为空;最简单的方法是为 this.file.name 甚至 this.file 创建默认/回退值。

// Fallback for this.file.name
async getUrl() {
    const filePath = `${this.basePath}/${this.file.name || 'fallback-filename'}`; // will not error, if undefined will use 'fallback-filename' instead.
    const snap = this.afStorage.storage.ref(filePath);
    await snap.getDownloadURL().then(url => {
        this.url = url;  //store the URL
        console.log(this.url);
    });
}

// Fallback for this.file, i.e. instantiate file with some data and have that overwritten
file: File = {
    name: 'fallback-filename',
    // ...
}