尝试在 Angular 中执行删除操作时出错
Getting error when trying to perform Delete operation in Angular
当我尝试在 angular CRUD 操作中执行删除操作时收到以下错误:“src/app/home/home.component.ts(29,37) 中的错误:错误TS2322: 类型 'Headers' 不可分配给类型 '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'});
当我尝试在 angular CRUD 操作中执行删除操作时收到以下错误:“src/app/home/home.component.ts(29,37) 中的错误:错误TS2322: 类型 'Headers' 不可分配给类型 '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'});