无法在httpclient中设置自定义标头(ionic 3应用程序角度为5)

时间:2019-02-13 08:32:23

标签: angular api ionic-framework ionic3 angular5

我正在尝试使用需要API密钥“ Auth”的api,我正在尝试使用以下代码通过httpHeaders发送密钥

getTest(){
let data = {'loginusertype':'12','loginuserid':'51','apitype':'1','start':'0','end':'20'};
let headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8','Auth':'593eb2c274d640a8798493bf340e08b6'});
this.http.post('http://www.mymediaxchange.com/api/serviceapi/v1/currentworks',data,{headers:headers})
.subscribe(
  (data) => console.log(data),
  (error) => console.log(error)
)  }

但是我无法设置标题,标题设置如下enter image description here

我尝试过的事情
1)二手拦截器
2)此问题的解决方案
Angular HttpClient doesn't send header
3)this.http.post('mymediaxchange.com/api/serviceapi/v1/currentworks',data,{headers: {'Auth': 'YourAuthorizationKey'}})

1 个答案:

答案 0 :(得分:0)

您可以尝试使用拦截器服务。它的作用是,向您的应用程序中的每个请求添加一个Authorization标头。

var admin = require("firebase-admin");

// Fetch the service account key JSON file contents
var serviceAccount = require("path/to/serviceAccountKey.json");

// Initialize the app with a service account, granting admin privileges
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://databaseName.firebaseio.com"
});

// As an admin, the app has access to read and write all data, regardless of Security Rules
var db = admin.database();
var ref = db.ref("restricted_access/secret_document");
ref.once("value", function(snapshot) {
  console.log(snapshot.val());
});

并在您的模块提供商部分中使用它。

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // add authorization header with token
    const currentUser = JSON.parse(String(localStorage.getItem('currentUser')));
    if (currentUser && currentUser.Token) {
      request = request.clone({
        setHeaders: {
          Authorization: `${currentUser.Token}`
        }
      });
    }
    return next.handle(request);
  }
}