Angular Как удалить фотографию из ошибки рецепта. Невозможно прочитать свойство "склейка" из неопределенного - PullRequest
0 голосов
/ 28 февраля 2020

Я пытаюсь удалить фотографию из моего рецепта, и это удаляет элемент, но у меня появляется ошибка: «Не удается прочитать свойство« склейка »из неопределенного» Фотография удалена, но я не вижу должного предупреждения. Чтобы увидеть эффект, я должен обновить страницу sh. Что я должен делать?

в моем сервисе:

deletePhoto(userId: number, recipeId: number, id: number) {
  return this.http.delete(this.baseUrl + 'users/' + userId + '/recipes/' + recipeId + '/photos/' + id);
}

в моем компоненте:

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';

@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[];

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

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



  updateRecipe(id: number) {
    this.recipeService.editRecipe(this.authService.decodedToken.nameid, id, this.recipe).subscribe(next => {
      this.alertify.success('Recipe updated successfully');
      this.editForm.reset(this.recipe);
    }, error => {
      this.alertify.error(error);
    });
  }

  deletePhoto(id: number) {
    this.alertify.confirm('Are you sure you want to delete this photo?', () => {
      this.recipeService.deletePhoto(this.authService.decodedToken.nameid, this.recipe.id, id).subscribe(() => {
        this.photos.splice(this.photos.findIndex(p => p.id === id), 1);
        this.alertify.success('Photo has been deleted');
      }, error => {
        this.alertify.error('Failed to delete the photo');
      });
    });
  }

}

recipe-edit-component. html

  <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>

Ответы [ 2 ]

1 голос
/ 28 февраля 2020

Я предполагаю, что фотографии на самом деле заполнены как часть рецепта. Если это так, измените:

 this.photos.splice(this.photos.findIndex(p => p.id === id), 1);

на

 this.recipe.photos.splice(this.recipe.photos.findIndex(p => p.id === id), 1);
0 голосов
/ 28 февраля 2020

Попробуйте разделить его на два этапа следующим образом:

let index = this.photos.findIndex(p => p.id === id);
this.photos = this.photos.splice(index , 1);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...