Angular 6删除函数报错返回undefined,求代码问题排查与解决
问题排查与解决方案
我来帮你排查代码里的问题,同时实现带确认提示的删除功能~
先看你代码里的几个核心错误
- 参数类型不匹配:
data.service.ts中的deleteMovie方法定义接收的是Movie类型参数,但在movie-list.component.ts调用时传的是movie.Id(数字类型),这直接导致类型错误,触发请求失败。 - 接口地址无效:你的
baseUrl设为http://localhost:4200/,这是Angular本地开发服务器地址,它并没有提供处理电影删除的DELETE接口,所以即使参数正确,也会返回404错误。 - 缺少错误处理:订阅
deleteMovie时没有错误回调,报错时无法定位问题原因。
修复代码 + 实现带提示的删除功能
下面是修正后的完整代码,同时添加了删除确认提示:
1. 修正data.service.ts的deleteMovie方法
我们先调整参数类型,同时如果暂时没有真实后端接口,先模拟请求(后续有真实接口时替换即可):
import { Movie } from './model/movie.model'; import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; @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); } // 修正参数为数字类型,模拟删除请求(替换为真实接口请注释掉这段,打开下面的HTTP请求) deleteMovie(movieId: number): Observable<boolean> { return new Observable(observer => { setTimeout(() => { observer.next(true); observer.complete(); }, 500); }); // 真实后端接口示例 // return this.http.delete<boolean>(`${this.baseUrl}api/movies/${movieId}`); } }
2. 修正movie-list.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 { // 弹出确认提示框 if (confirm(`确定要删除电影《${movie.Title}》吗?`)) { this.dataService.deleteMovie(movie.Id) .subscribe({ next: () => { // 从前端数组中移除对应电影 this.movies = this.movies.filter(u => u.Id !== movie.Id); alert('电影删除成功!'); }, error: (err) => { console.error('删除请求失败:', err); alert('删除失败,请稍后重试!'); } }); } } }
3. 模板中的删除按钮(补充)
确保你的movie-list.component.html里的删除按钮正确绑定方法:
<div *ngFor="let movie of movies" class="movie-item"> <h3>{{movie.Title}}</h3> <p>上映年份:{{movie.Year}}</p> <button (click)="deleteMovie(movie)" class="delete-btn">删除</button> </div>
可选优化:用Angular Material做美观的确认弹窗
如果你的项目使用Angular Material,可以替换原生提示为更友好的弹窗:
- 先在模块中导入
MatDialogModule - 创建一个确认弹窗组件
ConfirmDeleteDialogComponent - 修改组件中的删除逻辑:
import { MatDialog } from '@angular/material/dialog'; // ...其他导入 constructor(private dataService: DataService, private dialog: MatDialog) {} deleteMovie(movie: Movie): void { const dialogRef = this.dialog.open(ConfirmDeleteDialogComponent, { data: { movieTitle: movie.Title } }); dialogRef.afterClosed().subscribe(confirmed => { if (confirmed) { this.dataService.deleteMovie(movie.Id) .subscribe({ next: () => this.movies = this.movies.filter(u => u.Id !== movie.Id), error: err => console.error('删除失败:', err) }); } }); }
这样处理后,点击删除按钮会先弹出确认提示,确认后才会执行删除操作,同时从前端数组中移除对应电影,还能处理请求错误。
内容的提问来源于stack exchange,提问作者Ava Sahal
相关产品推荐
相关产品推荐

