首页 > 解决方案 > 删除函数错误Angular 6返回未定义

问题描述

我正在尝试编写一个删除函数来从我的对象中删除一部电影。

这是我的代码,但是当我单击删除按钮时,我得到 DELETE:错误。

您认为我的代码中的错误是什么?

你可以在这里查看我的代码...

电影模型.ts

export class Movie {
  Id: number;
  Title: string;
  Year: number;
  Runtime: string;
  Genre: string;
  Director: string;
}

数据服务.ts

import { Movie } from './model/movie.model';

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(private http: HttpClient) { }
  baseUrl: string = 'http://localhost:4200/';

  getMovies() {
    return fetch('https://www.omdbapi.com/?i=tt3896198&apikey=9fa6058b').then(function (resp) {
      return resp.json()
    });
  }

  createMovie(movie:Movie) {
    return this.http.post(this.baseUrl, movie);

  }

  deleteMovie(movie:Movie){
    return this.http.delete(this.baseUrl + movie.Id);
  }


}

电影列表.component.ts

import { DataService } from './../data.service';
import { Movie } from './../model/movie.model';
import { Component, OnInit } from '@angular/core';


@Component({
  selector: 'app-movie-list',
  templateUrl: './movie-list.component.html',
  styleUrls: ['./movie-list.component.css']
})
export class MovieListComponent implements OnInit {

  movies = [
    {Id:1, Title: 'Avatar', Year: '2009'},
    {Id:2, Title: 'Harry Potter', Year: '2001'},
    {Id:3, Title: 'Spiderman 3', Year: '2007'}
  ];

  constructor(private dataService:DataService){}

  ngOnInit() {
    this.getMovie().then(dt => {
      this.movies.push(dt);

    })
  }

  getMovie() {
    return fetch('https://www.omdbapi.com/?i=tt3896198&apikey=9fa6058b').then(function (resp) {
      return resp.json()
    });
  }

  deleteMovie(movie: Movie): void {
    this.dataService.deleteMovie(movie.Id)
      .subscribe( data => {
        this.movies = this.movies.filter(u => u !== movie);
      })
  };
}

这是我得到的错误...

在此处输入图像描述

我该怎么做才能让删​​除按钮工作并给我一个警报,然后从对象中删除它自己?

标签: javascripthtmlangulartypescript

解决方案


您尝试访问实际运行 Angular 应用程序的端点:baseUrl: string = 'http://localhost:4200/';这是本地计算机上 Angular 应用程序的默认端口,我猜您尝试调用外部 rest api 的删除端点。

但是其余服务无法在您的 localhost 上的 4200 端口上运行,这就是您找不到 404 的原因。我认为您必须在此端点上调用 delete https://www.omdbapi.com

编辑:

如果要从列表中删除电影,则必须删除数组中的条目。最简单的方法是将id属性更改为,imdbID因为来自 omdbapi 的响应类型没有 id 属性,这意味着您的 id 将始终未定义。然后当你想删除一个条目时,你可以这样做:

 deleteMovie(imdbID: string): void {
    this.movies = this.movies.filter(m => m.imdbID !== imdbID)
  };

它几乎与您拥有的代码相同,但在其余 api 上没有删除调用。因为您不想从数据库中删除条目,而只是在您的 Angular 应用程序上。


推荐阅读