如何为Ionic 2中的所有请求设置默认Http标头? [英] How do I set default Http Headers for all requests in Ionic 2?

查看:356
本文介绍了如何为Ionic 2中的所有请求设置默认Http标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了如何设置Default Http Headers我的所有请求,我发现如何使用 bootstrap 函数在Angular 2中实现,但它在Ionic中不可用2,如本问题中所述如何在Angular2中设置默认HTTP标头?

I've searched how to set up Default Http Headers all my request and I found how to implement in in Angular 2 with bootstrap function, but it's not available in Ionic 2, as described in this question How to set default HTTP header in Angular2?.

我想将 Content-Type 标头设置为 application / json 而不是按请求设置

I want to set Content-Type header to application/json instead of setting it up in per-request

我一直试图覆盖 BaseRequestOptions 并在我的应用程序中注入它们,但我无法覆盖它们。

I have been trying to override BaseRequestOptions and injecting them in my App, but I cannot get to override them.

app.ts

...
import {BaseRequestOptions, Headers, HTTP_PROVIDERS, Http, RequestOptions} from '@angular/http';

@Injectable()
export class MyRequestOptions extends BaseRequestOptions{
    headers:Headers = new Headers({
        'Content-Type': 'application/json; charset=UTF-8'
    });
}

@App({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  config: {},
  providers: [HTTP_PROVIDERS, MyRequestOptions]
})
export class MyApp {
  rootPage: any = HomePage;

  constructor(platform: Platform) {
     // init
  }
}

myService.ts

import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';

@Injectable()
export class MyService {
    constructor(private http: Http) {
    }

    getUser(id) {
         return this.http.post('/api/User/Get/', JSON.stringify({ id: id }));
    }
}

我缺少一些东西,我使用错了供应商注入?

There's something I'm missing, am I using wrong the providers injection?

推荐答案

您没有注册 MyRequestOptions 正确:

import { provide } from '@angular/core';
import { HTTP_PROVIDERS, RequestOptions, BaseRequestOptions, Headers } from '@angular/http';

...
@App({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  config: {},
  providers: [HTTP_PROVIDERS, provide(RequestOptions, { useClass: MyRequestOptions })]
})

或者您可以尝试通过地图文字注册提供商,如下所示:

Or you can try to register provider via map literal like this:

{ provide: RequestOptions, useClass: MyRequestOptions }

这篇关于如何为Ionic 2中的所有请求设置默认Http标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆