Angular 4:http客户端模块获取请求。 API密钥放置

时间:2017-12-22 20:13:38

标签: angular get httpclient

在离子/角度4中使用HttpClientModule进行api调用时,我在哪里放api键?我打电话的网站说使用curl这个curl命令:

curl -X GET https://jsonodds.com/api/odds -H "JsonOdds-API-Key: 
yourapikey"

如何更改此代码以包含api密钥?:

 apiUrl = "https://jsonodds.com/api/odds/nfl"

 getNFL() {
   return new Promise(resolve => {
     this.http.get(this.apiUrl).subscribe(data => {
     resolve(data);
   },   err => {
  console.log(err);
   });
 });

3 个答案:

答案 0 :(得分:1)

使用以下代码:

apiUrl = "https://jsonodds.com/api/odds/nfl"

 getNFL() {
   return new Promise(resolve => {
     this.http.get(this.apiUrl, { headers: new HttpHeaders().set("JsonOdds-API-Key", "your-api-key")).subscribe(data => {
     resolve(data);
   },   err => {
  console.log(err);
   });
 });

希望它会有所帮助

答案 1 :(得分:1)

使用自定义拦截器,可以将api密钥自动添加到每个http调用。如果你想了解更多有关拦截器here的信息,那就是开始阅读。

apikey.interceptor.ts

import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class ApiKeyInterceptor implements HttpInterceptor {
  constructor() {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    // add the header to the cloned request
    const authReq = req.clone({headers: req.headers.set('JsonOdds-API-Key', 'yourapikey')});

    return next.handle(authReq);
  }
}

不要忘记在AppModule

中注册拦截器

app.module.ts

import {NgModule} from '@angular/core';
import {HTTP_INTERCEPTORS} from '@angular/common/http';

import {ApiKeyInterceptor} from 'apikey.interceptor';

@NgModule({
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: ApiKeyInterceptor,
    multi: true,
  }],
})
export class AppModule {}

答案 2 :(得分:0)

import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'JsonOdds-API-Key', 'yourapikey'
  })
};

 apiUrl = "https://jsonodds.com/api/odds/nfl"

 getNFL() {
   return new Promise(resolve => {
     this.http.get(this.apiUrl,httpOptions ).subscribe(data => {
     resolve(data);
   },   err => {
  console.log(err);
   });
 });

//new HttpHeaders().set method is used to return a clone of the current instance with the new changes applied.