Observable HttpEvent在Typescript中不能分配给Observable类型



我调用REST API从我的我在typescript中编写了以下服务类. 我想调用不同的url并传递不同的基于环境选择。例如:如果环境是dev那么userURL的值应该是http://mydomain-dev.com/users/应为devHttpOptions,同样适用于QA-userURL应该是http://mydomain-qa.com/users/应该是qaHttpOptions

我在开关箱下面写了语句,基于环境值,我决定哪个url头和

但是当我在get中传递this.httpOptions时,我得到了低于编译时的错误method -this.http.get<User[]>(this.userURL, this.httpOptions)

Type 'Observable<HttpEvent<User[]>>' is not assignable to type 'Observable<User[]>'.
Type 'HttpEvent<User[]>' is not assignable to type 'User[]'.
Type 'HttpSentEvent' is missing the following properties from type 'User[]': length, pop, push, concat, and 28 more.ts(

请找到我的代码如下:

UserService.ts

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
import { User } from "./user";
import { HttpHeaders } from '@angular/common/http';

@Injectable({ providedIn: 'root' })
export class UserService {
constructor(private http: HttpClient) { }
userURL: any;
httpOptions: any;
devHttpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa('dev-xxxx:yyyy')
})
};
qaHttpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa('qa-xxxx:yyyy')
})
};
prodHttpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa('prod-xxxx:yyyy')
})
};

getUsers(environment): Observable<User[]> {
console.log(environment);
switch (environment) {
case 'dev':
this.userURL = 'http://mydomain-dev.com/users/';
this.httpOptions = this.devHttpOptions;
break;
case 'qa':
this.userURL = 'http://mydomain-qa.com/users/';
this.httpOptions = this.qaHttpOptions;
break;
case 'prod':
this.userURL = 'http://mydomain-prod.com/users/';
this.httpOptions = this.prodHttpOptions;
break;
}
return this.http.get<User[]>(this.userURL, this.httpOptions);
}
}

你能帮我解决这个问题吗?提前感谢您的帮助!谢谢!

http headers在类型为any的httpoptions变量中找不到,所以您可以直接这样使用它。你应该这样做:

return this.http.get<User[]>(this.userURL, {
headers: this.httpOptions?.headers
});

您可以在这里看到get()的所有重载:

https://angular.io/api/common/http/HttpClient得到

它不知道httpOptions是一个对象,所以它使用了错误的重载。当您使用any时,默认是第一个与get<T>匹配的重载,它返回Observable<HttpEvent<T>>。如果你声明一个对象没有observe属性,它将使用你想要的重载,因为observe是一个可选的属性,而在其他对象上是必需的。

httpOptions初始化为对象或声明为对象。

httpOptions = {};

httpOptions: Object;

或者您可以将observe: 'body'放在options对象上。这将显式地选择您想要的重载。

httpOptions: any;
getUsers(environment) {
...
return this.http.get<User[]>(this.userURL, {
...this.httpOptions,
observe: 'body',
});
}

相关内容

最新更新