javascript - Angular JS TypeScript IHttpService 注入(inject)自定义 header 值

标签 javascript angularjs http header typescript

我有一个项目,我成功地从 TypeScript(Angular HTTP 服务)代码到 Web API Controller 发出 Http Get 请求,并在网格中显示列表。该项目成功使用 Angular JS 1.4.x 和 TypeScript。

完整项目的 GitHub URL . 下面是调用服务器的 TypeScript 代码。

module App {
    export class StudentListService {
        private qService: ng.IQService;
        private httpService: ng.IHttpService;

        constructor($q: ng.IQService, $http: ng.IHttpService) {
            this.qService = $q;        
            this.httpService = $http;
        }

        get(): ng.IPromise<Object[]> {
            var self = this;
            var deffered = self.qService.defer();            
            self.httpService.get('/api/values').then((result: any): void => {
                if (result.status === 200) {
                    deffered.resolve(result.data);
                } else {
                    deffered.reject(result);
                }
            }, error => {
                deffered.reject(error);
            });

            return deffered.promise;
        }
    }

    StudentListService.$inject = ['$q', '$http'];
    angular.module('app').service('StudentListService', StudentListService);
}

现在,我想通过 get 请求调用添加自定义 header 。我尝试了很多方法,但 TypeScript 一直给我构建错误。任何帮助或解决方法将不胜感激。

最佳答案

只要您使用正确的 Angular 输入文件,您就应该能够将 header 添加为配置的一部分,第二个参数的类型为 ng.IRequestShortcutConfig这是 IHttpProviderDefaults 的扩展有 header属性(property)。

get<T>(url: string, config?: IRequestShortcutConfig): IHttpPromise<T>;

还添加了很多简化的代码。

      export class StudentListService {

        static $inject = ['$q', '$http'];

        constructor(private qService: angular.IQService, 
                    private httpService: angular.IHttpService) { }

        get(): angular.IPromise<Object[]> {

            //Example of config structure
            var config: angular.IRequestShortcutConfig = {
                headers: {
                    "someheader":"somevalue"
                }
            }
            //add config and just return the promise directly instead of creating a deferred object. Promises are chainable
            return this.httpService.get('/api/values', config)
              .then((result: any) => result.data);

              //If you want to catch then use ".catch" instead of second argument to the "then" which is a better practice as any error that may happen inside your code in the then block will be caught as well.
        }
    }

关于javascript - Angular JS TypeScript IHttpService 注入(inject)自定义 header 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33281984/

相关文章:

javascript - 初学者很难使用简单的下拉菜单

javascript - 某些 CSS 属性不适用于此脚本

html - div 的 CSS 高度和 Angular UI 路由

javascript - 使用 $.each 进行表单验证

http - 如何检查所有 “Not Secure” 页面?

javascript - 通过电子邮件激活用户

javascript - 温度程序简单转换

javascript - glob-fs glob.readdirSync 的意外行为

angularjs - 未定义不是函数是 CoffeeScript/Angular/Jasmine

python - Django StreamingHttpResponse 格式错误