javascript - 删除函数错误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);
})
};
}
这是我得到的错误...
我该怎么做才能让删除按钮工作并给我一个警报,然后从对象中删除它自己?
解决方案
您尝试访问实际运行 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 应用程序上。
推荐阅读
- html - 为什么我的外部样式表没有链接到移动设备上?
- reactjs - React Hooks:如何将我的 AuthUserRole(基于角色的身份验证)组件 (HOC) 变成 React Hook?
- c++11 - 使用可变参数模板和移动语义
- java - Gradle:查找哪些模块依赖于特定模块
- r - 使用 Rvest 抓取 HTML:无法提取文本
- opencv - 开放式简历。如何仅通过透视检测这 3 个正方形中的一个来绘制 3x1 精确正方形网格的 4 个角的 3 种可能性?
- trend - 趋势雷达数据
- python - 展平复杂的嵌套 JSON
- bash - Sed/Tr 对 api 输出进行排序
- python - 如果满足条件,则为子组分配值