我们正在编写一个基于离子的应用程序。我们需要在每个请求上附加标题api_token
和api_key
。
目前我们做的事情很难看
getUserProfile(apiToken, apiKey)
//fetch user profile
getUserProfile(api_key: string, api_token: string): Observable<any> {
let headers = new Headers();
headers.append("API_KEY", api_key);
headers.append("API_TOKEN", api_token);
headers.append("Content-Type", "application/x-www-form-urlencoded");
let options = new RequestOptions({headers: headers})
return this.http.get(UrlService.getUrlUserProfile(), options)
.map(res => res.json())
.catch((error: any) => Observable.throw(error));
}
总的来说,我们将有大约450个请求,我拒绝附加每个标题。我是一个红宝石开发人员,在ruby中我会简单地覆盖该方法,如果我们有值并且调用super
,则抛出标题。
我发现JavaScript中存在类似的技术,但我不确定
遗憾的是,我无法找到有关该主题的任何文档或SO问题。
我在base_request_options.d.ts
文件夹中找到ionic/net
,但似乎我无法在那里注入我的标题。那甚至是正确的位置吗?
//编辑
我在这个问题上获得了100个声誉奖,因为它会对我们有很大帮助。 摘要:
我们需要将api_key和api_token附加到每个PUT / POST / DELETE / GET请求。我们只想在代码中的1个地方附加这个,而不是我们正在构建的每个请求。
答案 0 :(得分:1)
您可以创建一个调用http.get
的公共函数,并从每个函数中调用该公共函数
你打电话给http.get
的地方。这也适用于所有PUT/POST/DELETE/GET
用户profile.service.ts
import { UtilService } from '/path-to/util.service';
...
constructor(
private util: UtilService,
...
)
...
//fetch user profile
getUserProfile(): Observable<any> {
// Call the common get function we define in below file
return this.util.get(UrlService.getUrlUserProfile());
}
utils.service.ts
export class UtilService {
...
get(url: string): Observable<any> {
let headers = new Headers();
// Here I am assuming that you store it in localStorage for global access
headers.append("API_KEY", localStorage.getItem("api_key"));
headers.append("API_TOKEN", localStorage.getItem("api_token"));
headers.append("Content-Type", "application/x-www-form-urlencoded");
let options = new RequestOptions({headers: headers})
return this.http.get(url, options)
.map(res => res.json())
.catch((error: any) => Observable.throw(error));
}
post(url: string, data: any): Observable<any> {
let headers = new Headers();
headers.append("API_KEY", localStorage.getItem("api_key"));
headers.append("API_TOKEN", localStorage.getItem("api_token"));
headers.append("Content-Type", "application/x-www-form-urlencoded");
let options = new RequestOptions({headers: headers})
return this.http.post(url, data, options)
.map(res => res.json())
.catch((error: any) => Observable.throw(error));
}
...
// Do the same for put, delete etc..
}
现在您可以在不传递任何参数的情况下调用getUserProfile
:
some.component.ts
getUserProfile().subscribe((res: any) => {
console.log(res);
// Do whatever you want
}, (err: any) => {
console.log(err);
// Some error toast etc..
})
答案 1 :(得分:1)
使用以下代码。
import {Injectable} from "@angular/core";
import { ConnectionBackend, RequestOptions, Request, RequestOptionsArgs, Response, Http, Headers} from "@angular/http";
import {Observable} from "rxjs/Rx";
@Injectable()
export class InterceptedHttp extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
url = this.updateUrl(url);
return super.get(url, this.getRequestOptionArgs(options));
}
post(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
url = this.updateUrl(url);
return super.post(url, body, this.getRequestOptionArgs(options));
}
put(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
url = this.updateUrl(url);
return super.put(url, body, this.getRequestOptionArgs(options));
}
delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
url = this.updateUrl(url);
return super.delete(url, this.getRequestOptionArgs(options));
}
private updateUrl(req: string) {
return req;
}
private getRequestOptionArgs(options?: RequestOptionsArgs) : RequestOptionsArgs {
if (options == null) {
options = new RequestOptions();
}
if (options.headers == null) {
options.headers = new Headers();
}
const headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Access-Control-Allow-Headers', 'Content-Type');
headers.append('Access-Control-Allow-Methods', 'GET');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('details', 'abc');
options = new RequestOptions({ headers: headers });
//options.headers.append('Content-Type', 'application/json');
return options;
}
}