【问题标题】:angular post work 2nd time ord 3rd time HTTP Post角度发布工作第二次或第三次 HTTP Post
【发布时间】:2024-05-20 12:15:01
【问题描述】:

我知道这是异步的问题,但是如果我添加了 .subscribe 并且我正在等待消息,为什么我会遇到这个问题

我的代码

public redirectToDelete = (id: string) => {
      this.carService.getId(id).subscribe(result =>
         new alert(this.carService.delete(result)));
   }

这里是删除

deleteUrl = "/car/delete.php";
    delete(car: Car): any {
        this.http.post(this.deleteUrl, car)
        .subscribe(res => {
            return res;
        },
            (error => {
                return error;
            })
        )
        return "";
    }

【问题讨论】:

  • @Igor 我会检查的。目前我正在学习角度:)

标签: angular


【解决方案1】:
  • 您需要返回 observable:return this.http.post(this.deleteUrl, car)....。否则,您将尝试在空字符串上调用 subscribe
  • 您还应该在您的方法中指定返回类型而不是 any,这样您就有类型安全性,这是使用 typescript 的主要好处之一。
  • 您的delete 方法应该返回可观察对象,而不是订阅。直接将电话回拨给post
  • 使用HttpClient 中的泛型重载来确保类型安全。
delete(car: Car): Observable<YourTypeHere> {
    return this.http.post<YourTypeHere>(this.deleteUrl, car);
}
import { switchMap } from 'rxjs/operators';


public redirectToDelete = (id: string) => {
      this.carService.getId(id)
          .pipe(switchMap(r => this.carService.delete(r))) // ← switchMap is handy here, alternatively you could call the next service end point in a subscribe and then have a nested subscribe but this makes for messier code IMO
          .subscribe(result => new alert(result));
   }

附带说明,如果您正在构建一个提供删除功能的 RESTful 服务,那么我建议您设置一个使用 http DELETE 动词而不是 post 的端点。

【讨论】:

  • 最后一个元素有个小问题我不能删除
最近更新 更多