如何在Angular 5中添加接受标头?
我正在使用GitHub API在GitHub存储库中显示Projects。 GitHub API documentation说要使用它,我必须在Accept标头中提供自定义媒体类型。
这是我的代码。它当前返回不支持的媒体类型错误。
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { GitIdInfo, GitRepo, GitProject} from './github-id';
import { Observable } from 'rxjs/Observable';
const githubAPI = 'https://api.github.com/';
@Injectable()
export class GitIdInfoService {
constructor(private http: HttpClient) { }
GetGitProj(login, Repo: String): Observable<GitProject[]>{
const userProject = githubAPI + 'repos/';
return(this.http.get<GitProject[]>(userProject + login + '/' + Repo + '/projects'));
}
}
以下是我将以最简单的格式设置的方法
GetGitProj(login, Repo: String): Observable<GitProject[]>{
const userProject = githubAPI + 'repos/';
let header = new Headers({'content-Type': 'application/json'});
let options = new RequestOptions({headers: header});
return(this.http.get<GitProject[]>(userProject + login + '/' + Repo + '/projects', options));
}
这里有点复杂但使用方便
GetGitProj(login, Repo: String): Observable<GitProject[]>{
const userProject = githubAPI + 'repos/';
let header: Args[] = [
{id: "Authorization", val: "ahjsbdhaskajsd"},
{id: "Accept", val: "value"}
];
return(this.http.get<GitProject[]>(userProject + login + '/' + Repo + '/projects', this.addHeader(header)));
}
/***
* Generates default headers I.E. #content-Type and append any optional headers provided
* @param {Args[]} args an array of Args[KEY, Value]
* @returns {Headers}
*/
private addHeader(args: Args[]): Headers {
let headers: Headers = new Headers();
let a: Args = new Args;
a.id = "content-Type";
a.val = "application/json";
headers.append(a.id, a.val);
if (args == null) return headers;
args.forEach(a => {
headers.append(a.id, a.val);
});
return headers;
}
这是使用新的风格:
GetGitProj(login, Repo: String): Observable<GitProject[]>{
const userProject = githubAPI + 'repos/';
return(this.http.get<GitProject[]>(userProject + login + '/' + Repo + '/projects', {headers: new HttpHeaders().set('content-Type', 'value')}));
}