我有这样的服务:
import { Injectable } from "@angular/core";
import { Http, Response, Headers, RequestOptions } from "@angular/http";
import "rxjs/add/operator/map";
import { Usuario } from "../_models/usuarios";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs/Observable";
import { User } from "../_models/user.model";
private serviceUrl = "apiUrl";
headers = new Headers({
Authorization:
"Bearer " + JSON.parse(localStorage.getItem("currentUser")).token,
"Content-Type": "application/json"
});
options = new RequestOptions({ headers: this.headers });
constructor(private http: Http, private httpClient: HttpClient) {}
getUser(): Observable<User[]> {
return this.httpClient.get<User[]>(this.serviceUrl);
}
问题是当我尝试发送选项以获取方法时:
getUser(): Observable<User[]> {
return this.httpClient.get<User[]>(this.serviceUrl, this.options);
}
它返回:
消息:&#39;类型&#39; RequestOptions&#39;不能转让给 参数类型&#39; {headers?:HttpHeaders | {[header:string]: 字符串|串[]; };观察?:&#34;身体&#34 ;; params?:Ht ......&#39;。种类 财产&#39;标题&#39;是不相容的。 输入&#39;标题&#39;不能分配给&#39; HttpHeaders | {[header:string]:string |串[]; }&#39 ;. 输入&#39;标题&#39;不能分配类型&#39; {[header:string]:string |串[]; }&#39 ;. 类型&#39; Headers&#39;&#39;
中缺少索引签名
我尝试使用http代替httpClient来改变它:
return this.http.get<User[]>(this.serviceUrl, this.options);
但现在我得到了
消息:&#39;预期0类型参数,但得到1。&#39;
我做错了什么?
答案 0 :(得分:0)
如果你使用httpClient,你应该
import { HttpHeaders } from '@angular/common/http';
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': "Bearer " + JSON.parse(localStorage.getItem("currentUser")).token
})
}
...
getUser(): Observable<User[]> {
return this.httpClient.get<User[]>(this.serviceUrl,httpOptions);
}
答案 1 :(得分:0)
您可以使用HttpClient
@angular/common/http
这样的内容:
import { Injectable } from "@angular/core";
import { Usuario } from "../_models/usuarios";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Observable } from "rxjs";
import { User } from "../_models/user.model";
@Injectable()
export class UserService{
private serviceUrl = "apiUrl";
headers = new HttpHeaders({
Authorization: "Bearer " + JSON.parse(localStorage.getItem("currentUser")).token,
"Content-Type": "application/json"
});
constructor(private httpClient: HttpClient) {}
getUser(): Observable<User[]> {
return this.httpClient.get<User[]>(this.serviceUrl, { 'headers': this.headers});
}
}