簡體   English   中英

Angular TypeError:無法讀取未定義的屬性“名稱”

[英]Angular TypeError: Cannot read property 'name' of undefined

我想做的是分開兩種方法。 但這給我帶來了一個問題。 當我試圖讓 function 在組件初始化上運行時。 我想在上傳文件時獲取文件名並將數據從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);
    });
  }
}

用戶配置文件.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)

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

看來getUrl()方法希望this.file.name在它被調用時定義。

一個簡單的解決方法是僅當您知道this.file上的name屬性具有值時才調用getUrl() ,例如

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

或更簡單地使用 null 檢查

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',
    // ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM