gpt4 book ai didi

angular - 类型 header 不可分配给 TypeScript 和 Angular 9 中的 HttpHeaders 类型

转载 作者:行者123 更新时间:2023-12-02 18:59:52 24 4
gpt4 key购买 nike

我是 TypeScript 新手,正在学习制作一个简单的身份验证教程。对于后端,我使用 Express,前端我使用 Angular 9。我对这个错误进行了很多研究,因为网上有很好的资源,但我不明白为什么没有一个适用于我的案例。

我收到以下错误:

Error: src/app/services/auth.service.ts:19:79 - error TS2769: Nooverload matches this call. The last overload gave the followingerror.Type 'Headers' is not assignable to type 'HttpHeaders | { [header: string]: string | string[]; } | undefined'.Type 'Headers' is not assignable to type '{ [header: string]: string | string[]; }'.Index signature is missing in type 'Headers'.

19 returnthis.httpCient.post('http://localhost:3000/users/register', user,{headers: headers}).pipe(map(res => res));

因此,在 registerUser(user)authenticate(user) 两个函数上,错误似乎都在这一行:

return this.httpCient.post('http://localhost:3000/users/authenticate', user, {headers: headers}).pipe(map(res => res));

下面是导致问题的代码:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
providedIn: 'root'
})
export class AuthService {
authToken: any;
user: any;

constructor(private httpClient: HttpClient) { }


registerUser(user) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.httpClient.post('http://localhost:3000/users/register', user, {headers: headers}).pipe(map(res => res));
}

authenticateUser(user) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.httpClient.post('http://localhost:3000/users/authenticate', user, {headers: headers}).pipe(map(res => res));
}
}

我找到了this post帮助我解决问题,但没有成功,因为我使用的是 Angular 9 并且 http 模块现在已替换为 HttpClient, HttpHeaders from '@angular/common/http';。所以我能够遵循并部分解决它。

This作为常识也很有用,但它涉及 Angular 2 并且找不到有用的答案。

如果有人遇到同样的错误,请分享如何解决它。

最佳答案

HttpClient 需要 HttpHeaders 作为参数。 (Headers 对象在引入 HttpClient 之前使用,并且它与 HttpClient 不兼容。)因此,例如以下示例可以工作:

const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
});
return this.httpClient.post('http://localhost:3000/users/authenticate', user, httpOptions);

请在此处查看更多详细信息和示例: https://angular.io/guide/http#adding-headers

不要忘记订阅返回的Observable,否则请求将不会被发送。 (可观察量是惰性的。)

关于angular - 类型 header 不可分配给 TypeScript 和 Angular 9 中的 HttpHeaders 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65709146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com