Angular-HTTPClientModule删除请求不起作用



我正在从我的angular应用程序中发出一个简单的删除请求,但没有发生任何事情,也没有出现任何错误。我的服务代码如下:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class TodoService {
todoUrl = 'https://example.herokuapp.com/api/todoDB/';
constructor(private http: HttpClient) { }
getTodo() {
return this.http.get(this.todoUrl);
}
postTodo(todoObject: any) {
return this.http.post(this.todoUrl , todoObject);
}
deleteTodo(id: any) {
const url = `${this.todoUrl}${id}`;
console.log(url);    // *** This is printing correct URL
return this.http.delete(url);
}
}

我的getTodo((和postTodo(。当我把console.log(URL(中的URL放在poster中时,它可以工作,但在我的应用程序中不工作。我在我的组件中使用以下代码来访问我的服务的deleteTodo((方法:

removeTodo(i: any) {
this.todoService.deleteTodo(this.todoArray[i]._id);
}

我删除服务器的路径:

//  Delete Todo
router.delete('/:id' , (req , res) => {
Todo.findById(req.params.id)
.then((todo) => todo.remove().then(() => res.json({success : true})))
.catch(err => res.json({success : false}).status(404))
});

您需要订阅Observable

你的问题的代码段:

removeTodo(i: any) {
this.todoService.deleteTodo(this.todoArray[i]._id).subscribe(e=>{
// Callback
// Perform Actions which are required after deleting the id from the TODO
});
}

附加参考:

https://www.pluralsight.com/guides/posting-deleting-putting-data-angular

https://angular.io/guide/http#making-a-delete-request

使用管道进行调试,修改代码以支持catchErrorthrowError

import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
deleteTodo(id: any) {
const url = `${this.todoUrl}${id}`;
return this.http.delete(url).pipe(
catchError((err) => {
console.log('error caught in service')
console.error(err);
return throwError(err);    //Rethrow it back to component
})
);
}

最新更新