尝试在 Angular 中执行删除操作时出错

问题描述

当我尝试在 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(); 
  }
}

解决方法

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

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...