【发布时间】: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();
}
}
【问题讨论】:
-
用于标头的类称为
HttpHeaders(angular.io/api/common/http/HttpHeaders)。示例:angular.io/guide/http#adding-headers
标签: angular typescript crud http-delete