【问题标题】:Getting error when trying to perform Delete operation in Angular尝试在 Angular 中执行删除操作时出错
【发布时间】:2021-04-11 06:25:42
【问题描述】:

当我尝试在 Angular CRUD 操作中执行删除操作时收到以下错误:“src/app/home/home.component.ts(29,37) 中的错误:错误 TS2322:键入“标题”不可分配给类型 'HttpHeaders | { [header: string]: string | string[]; }'。类型 'Headers' 不可分配给类型 '{ [header: string]: string | string[]; }'。 'Headers' 类型中缺少索引签名。”。代码如下:

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpResponse, HttpHeaders } from '@angular/common/http';  
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  products: any[];
  constructor(private http: HttpClient) {}
  id: number;
  private headers = new Headers({ 'Content-Type': 'application/json'});

  //Url to fetch data: http://localhost:3000/products
  getData(){
    this.http.get("http://localhost:3000/products")
      .subscribe(response=>{
        this.products = response as any[];
      });
  }

  deleteProduct(id){
    if(confirm("Are you sure?")){
      const url = `${"http://localhost:3000/products"}/${id}`;
      return this.http.delete(url, {headers: this.headers}).toPromise()
        .then(()=>{
          this.getData();
        })
    }
  }

  ngOnInit() {
    this.getData(); 
  }
}

【问题讨论】:

标签: angular typescript crud http-delete


【解决方案1】:

如错误消息中所述,期望类型是 HttpHeaders,而不是 Headers:

private headers = new HttpHeaders({ 'Content-Type': 'application/json'});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多