我有以下代码:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import { environment } from '../../../environments/environment';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
const SERVICE_URL = 'http://localhost:3000/';
@Injectable()
export class BackendService {
constructor(private client: HttpClient) { }
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
...
getUser(firstname): Observable<any> {
const API_URL = `${SERVICE_URL}/user/firstname/${firstname}`;
return this.client.get(API_URL, { headers: this.httpOptions }).pipe(
map((res: Response) => {
return res || {}
}),
catchError(this.handleError)
)
}
...
我收到以下错误:
No overload matches this call.
The last overload gave the following error.
Type '{ headers: HttpHeaders; }' is not assignable to type 'HttpHeaders | { [header: string]: string | string[]; }'.
Type '{ headers: HttpHeaders; }' is not assignable to type '{ [header: string]: string | string[]; }'.
Property 'headers' is incompatible with index signature.
Type 'HttpHeaders' is not assignable to type 'string | string[]'.
Type 'HttpHeaders' is missing the following properties from type 'string[]': length, pop, push, concat, and 25 more.
No overload matches this call.
Overload 1 of 2, '(selector: (err: any, caught: Observable<unknown>) => never): MonoTypeOperatorFunction<unknown>', gave the following error.
Argument of type '<T>(operation?: string, result?: T) => (error: any) => Observable<T>' is not assignable to parameter of type '(err: any, caught: Observable<unknown>) => never'.
Type '(error: any) => Observable<Observable<unknown>>' is not assignable to type 'never'.
Overload 2 of 2, '(selector: (err: any, caught: Observable<unknown>) => ObservableInput<unknown>): OperatorFunction<unknown, unknown>', gave the following error.
Argument of type '<T>(operation?: string, result?: T) => (error: any) => Observable<T>' is not assignable to parameter of type '(err: any, caught: Observable<unknown>) => ObservableInput<unknown>'.
Type '(error: any) => Observable<Observable<unknown>>' is not assignable to type 'ObservableInput<unknown>'.
Property '[Symbol.iterator]' is missing in type '(error: any) => Observable<Observable<unknown>>' but required in type 'Iterable<unknown>'.
如上所述,我已经设置了标题。我尝试手动设置标题没有任何作用。我该如何解决?
答案 0 :(得分:1)
您应该将HttpOptions
传递给get
方法,该方法在HttpHeaders
字段中可以有一个headers
的实例。相反,您将其包装两次。如果您JSON.stringify
正在传递的对象,您将得到类似的东西:
{
"headers" : {
"headers" : {
// your headers here
}
}
}
在getUser方法中,切换到类似以下内容:
getUser(firstname): Observable<any> {
const API_URL = `${SERVICE_URL}/user/firstname/${firstname}`;
return this.client.get(API_URL, this.httpOptions).pipe(
map((res: Response) => {
return res || {}
}),
catchError(this.handleError)
)
}
您的httpOptions
已经具有正确的类型。