如何上传照片(ng2-file-upload)Angular无法读取未定义的属性“ push”

BartolV9

我正在尝试为食谱上传新照片,这是可行的。照片正在上传,但是控制台出现错误,要查看新照片,我必须刷新浏览器。我使用asp.net核心作为模型和控制器,并使用角度作为视图如何解决此问题?

在此处输入图片说明

零件

import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { Recipe } from 'src/app/_models/recipe';
import { ActivatedRoute } from '@angular/router';
import { RecipeService } from 'src/app/_services/recipe/recipe.service';
import { AuthService } from 'src/app/_services/auth.service';
import { AlertifyService } from 'src/app/_services/alertify.service';
import { NgForm } from '@angular/forms';
import { RecipePhoto } from 'src/app/_models/recipePhoto';
import { FileUploader } from 'ng2-file-upload';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-recipe-edit',
  templateUrl: './recipe-edit.component.html',
  styleUrls: ['./recipe-edit.component.css']
})
export class RecipeEditComponent implements OnInit {
  @ViewChild('editForm', {static: true}) editForm: NgForm;
  recipe: Recipe;
  photos: RecipePhoto[];
  uploader: FileUploader;
  hasBaseDropZoneOver = false;
  baseUrl = environment.apiUrl;
  currentMain: RecipePhoto;

  constructor(private route: ActivatedRoute, private recipeService: RecipeService, private authService: AuthService,
              private alertify: AlertifyService) { }

  ngOnInit() {
    this.route.data.subscribe(data => {
      this.recipe = data.recipe;
    });
    this.initializeUploader();
  }

  public fileOverBase(e: any): void {
    this.hasBaseDropZoneOver = e;
  }

  initializeUploader() {
    this.uploader = new FileUploader({
      url: this.baseUrl + 'users/' + this.authService.decodedToken.nameid + '/recipes/' + this.recipe.id + '/photos',
      authToken: 'Bearer ' + localStorage.getItem('token'),
      isHTML5: true,
      allowedFileType: ['image'],
      removeAfterUpload: true,
      autoUpload: false,
      maxFileSize: 10 * 1024 * 1024
    });

    this.uploader.onAfterAddingFile = (file) => {file.withCredentials = false; };
    this.uploader.onSuccessItem = (item, response, status, headers) => {
      if (response) {
        const res: RecipePhoto = JSON.parse(response);
        const photo = {
          id: res.id,
          url: res.url,
          dateAdded: res.dateAdded,
          description: res.description,
          isMain: res.isMain
        };
        this.photos.push(photo);

        if (photo.isMain) {
          this.recipeService.changeRecipePhoto(photo.url);
          this.recipeService.currentRecipe.photoUrl = photo.url;
          this.recipe = this.recipeService.currentRecipe;
        }
      }
    };
  }
}

HTML

<div class="container">
  <div class="row">
    <div class="col-sm-2" *ngFor="let photo of recipe.recipePhotos">
      <img src="{{photo.url}}" class="img-thumbnail p-1" alt="">
      <div class="text-center">
        <button type="button" class="btn btn-sm btn-danger" 
        (click)="deletePhoto(photo.id)" >
        <i class="fa fa-trash-o"></i></button>
      </div>
    </div>
</div>
  <form #editForm="ngForm" id="editForm" (ngSubmit)="updateRecipe(recipe.id)" >
    <h5 class=" text-center mt-4">Description</h5>
    <textarea name="description"  cols=100% rows="6" class="form-contorl mt-2" 
      [(ngModel)]="recipe.description"></textarea>
      <h5 class=" text-center mt-2">Location Details:</h5>
      <div class="form-group mt-3">
        <label for="city">Name</label>
        <input class="form-control" type="text" name="name" [(ngModel)]="recipe.name">
      </div>
      <div class="form-group">
        <label for="country">Ingredients</label>
        <input class="form-control" type="text" name="country" [(ngModel)]="recipe.ingredients">
      </div>
  </form>  

  <button [disabled]="!editForm.dirty" form="editForm" class="btn btn-success btn-block">Save changes</button>



</div>
<div class="containter">
  <div class="row mt-3">

    <div class="col-md-3 mt-3">

        <h3>Add Photos</h3>

        <div ng2FileDrop
             [ngClass]="{'nv-file-over': hasBaseDropZoneOver}"
             (fileOver)="fileOverBase($event)"
             [uploader]="uploader"
             class="card  bg-faded p-3 text-center mt-3 mb-3 my-drop-zone">
             <i class="fa fa-upload fa-3x"></i>
            Drop Photos Here
        </div>



        Multiple
        <input type="file" ng2FileSelect [uploader]="uploader" multiple  /><br/>

        Single
        <input type="file" ng2FileSelect [uploader]="uploader" />
    </div>

    <div class="col-md-6 ml-5" style="margin-bottom: 40px" *ngIf="uploader?.queue?.length">

        <h3>Upload queue</h3>
        <p>Queue length: {{ uploader?.queue?.length }}</p>

        <table class="table">
            <thead>
            <tr>
                <th width="50%">Name</th>
                <th>Size</th>

            </tr>
            </thead>
            <tbody>
            <tr *ngFor="let item of uploader.queue">
                <td><strong>{{ item?.file?.name }}</strong></td>
                <td *ngIf="uploader.options.isHTML5" nowrap>{{ item?.file?.size/1024/1024 | number:'.2' }} MB</td>
                <td *ngIf="uploader.options.isHTML5">      
            </tr>
            </tbody>
        </table>

        <div>
            <div>
                Queue progress:
                <div class="progress mb-4" >
                    <div class="progress-bar" role="progressbar" [ngStyle]="{ 'width': uploader.progress + '%' }"></div>
                </div>
            </div>
            <button type="button" class="btn btn-success btn-s"
                    (click)="uploader.uploadAll()" [disabled]="!uploader.getNotUploadedItems().length">
                <span class="fa fa-upload"></span> Upload 
            </button>
            <button type="button" class="btn btn-warning btn-s"
                    (click)="uploader.cancelAll()" [disabled]="!uploader.isUploading">
                <span class="fa fa-ban"></span> Cancel 
            </button>
            <button type="button" class="btn btn-danger btn-s"
                    (click)="uploader.clearQueue()" [disabled]="!uploader.queue.length">
                <span class="fa fa-trash"></span> Remove 
            </button>
        </div>

    </div>

  </div> 
</div>

如果上传正常,为什么会出现此错误

bjdose

为了在上传新照片后显示照片,您必须将照片变量添加到配方变量中,因为您仅在ngOnInit方法上初始化了配方变量

  ngOnInit() {
    this.route.data.subscribe(data => {
     // you're initializing your recipe variable here
     // that's the reason why you can see your photos only on refreshing
      this.recipe = data.recipe;
    });
    this.initializeUploader();
  }

因为您正在循环输入HTML代码,所以recipe.recipePhotos。

<div class="col-sm-2" *ngFor="let photo of recipe.recipePhotos"> <!--<- here -->

您必须将新照片添加到recipe.recipePhotos变量中,而不是仅推送到照片中。

    this.uploader.onSuccessItem = (item, response, status, headers) => {
      if (response) {
        const res: RecipePhoto = JSON.parse(response);
        const photo = {
          id: res.id,
          url: res.url,
          dateAdded: res.dateAdded,
          description: res.description,
          isMain: res.isMain
        };
        // here you have your photos array after uploading a photo
        // whit the new photo uploaded
        this.photos.push(photo);

        // but actually you're looping in your HTML the recipe.recipePhotos
        // so you need to push the new photo into recipePhotos this way
        this.recipe.recipePhotos.push(photo);

        if (photo.isMain) {
          this.recipeService.changeRecipePhoto(photo.url);
          this.recipeService.currentRecipe.photoUrl = photo.url;
          this.recipe = this.recipeService.currentRecipe;
        }
      }

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Angular无法读取未定义的属性“ push”

来自分类Dev

Angular FormArray:无法读取未定义的属性“ push”

来自分类Dev

如何解决Angularjs TypeError:无法读取未定义的属性“ push”?

来自分类Dev

如何在angular2中从浏览器获取检查值(面对原始异常:无法读取未定义错误的属性“ push”)

来自分类Dev

无法读取未定义Angular 2的属性

来自分类Dev

Angular - Ionic 2 - 无法读取未定义的属性“订阅”

来自分类Dev

TypeError:无法读取未定义的JavaScript属性“ push”

来自分类Dev

合并数组时无法读取未定义的属性“ push”

来自分类Dev

无法读取未定义Javascript的属性“ push”

来自分类Dev

TypeScript:无法读取[null]中未定义的属性“ push”

来自分类Dev

react-router无法读取未定义的属性“ push”

来自分类Dev

react-router“无法读取未定义的属性“ push”

来自分类Dev

TypeError:无法读取JavaScript中未定义的属性“ push”

来自分类Dev

Typescript,React:TypeError:无法读取未定义的属性“ push”

来自分类Dev

NodeJS无法读取未定义的属性“ push”

来自分类Dev

TypeError:无法读取未定义ReactJS的属性“ push”

来自分类Dev

ReactJS钩子无法读取未定义错误的属性“ push”

来自分类Dev

捕获TypeError:无法读取未定义的属性“ push”

来自分类Dev

TypeScript:TypeError:无法读取未定义的属性“ push”

来自分类Dev

如何修复'TypeError:无法读取未定义的属性'then'TypeError:无法读取未定义的属性'then'...'

来自分类Dev

(Angular2 和 Typescript)Angular 的 DatePicker 无法读取未定义的属性“切换”

来自分类Dev

如何解决“无法读取未定义的属性'定义'”?

来自分类Dev

无法读取未定义的属性。如何定义?

来自分类Dev

Angular 7 CLI ng 生成组件错误:'无法读取未定义的属性'sourceRoot''

来自分类Dev

Angular:无法读取 NgbModal 的 ng-template 内未定义的属性“sendClassForm”

来自分类Dev

无法读取文件上传的未定义属性“0”

来自分类Dev

NgZone / Angular2 / Ionic2 TypeError:无法读取未定义的属性“运行”

来自分类Dev

Angular2-TypeError:无法读取(Typescript)中未定义的属性'Id'

来自分类Dev

无法读取Angular 2中的嵌套调用中未定义的属性“ subscribe”

Related 相关文章

  1. 1

    Angular无法读取未定义的属性“ push”

  2. 2

    Angular FormArray:无法读取未定义的属性“ push”

  3. 3

    如何解决Angularjs TypeError:无法读取未定义的属性“ push”?

  4. 4

    如何在angular2中从浏览器获取检查值(面对原始异常:无法读取未定义错误的属性“ push”)

  5. 5

    无法读取未定义Angular 2的属性

  6. 6

    Angular - Ionic 2 - 无法读取未定义的属性“订阅”

  7. 7

    TypeError:无法读取未定义的JavaScript属性“ push”

  8. 8

    合并数组时无法读取未定义的属性“ push”

  9. 9

    无法读取未定义Javascript的属性“ push”

  10. 10

    TypeScript:无法读取[null]中未定义的属性“ push”

  11. 11

    react-router无法读取未定义的属性“ push”

  12. 12

    react-router“无法读取未定义的属性“ push”

  13. 13

    TypeError:无法读取JavaScript中未定义的属性“ push”

  14. 14

    Typescript,React:TypeError:无法读取未定义的属性“ push”

  15. 15

    NodeJS无法读取未定义的属性“ push”

  16. 16

    TypeError:无法读取未定义ReactJS的属性“ push”

  17. 17

    ReactJS钩子无法读取未定义错误的属性“ push”

  18. 18

    捕获TypeError:无法读取未定义的属性“ push”

  19. 19

    TypeScript:TypeError:无法读取未定义的属性“ push”

  20. 20

    如何修复'TypeError:无法读取未定义的属性'then'TypeError:无法读取未定义的属性'then'...'

  21. 21

    (Angular2 和 Typescript)Angular 的 DatePicker 无法读取未定义的属性“切换”

  22. 22

    如何解决“无法读取未定义的属性'定义'”?

  23. 23

    无法读取未定义的属性。如何定义?

  24. 24

    Angular 7 CLI ng 生成组件错误:'无法读取未定义的属性'sourceRoot''

  25. 25

    Angular:无法读取 NgbModal 的 ng-template 内未定义的属性“sendClassForm”

  26. 26

    无法读取文件上传的未定义属性“0”

  27. 27

    NgZone / Angular2 / Ionic2 TypeError:无法读取未定义的属性“运行”

  28. 28

    Angular2-TypeError:无法读取(Typescript)中未定义的属性'Id'

  29. 29

    无法读取Angular 2中的嵌套调用中未定义的属性“ subscribe”

热门标签

归档