Angular JS TypeScript的IHttpService注入自定义头值

Angular JS TypeScript IHttpService inject custom header value

本文关键字:自定义 注入 IHttpService JS TypeScript Angular      更新时间:2023-09-26

我有一个项目,我使成功的Http Get请求从TypeScript (Angular Http Service)代码到Web API控制器并在网格中显示列表。该项目使用的是Angular JS 1.4。

完整项目的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请求调用的自定义头。我已经尝试了很多方法,但TypeScript一直给我构建错误。任何帮助或工作将非常感激。

只要你使用正确的angular类型文件,你应该能够添加头文件作为配置的一部分,第二个参数类型是ng.IRequestShortcutConfig,这是IHttpProviderDefaults的扩展,具有header属性。

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.
        }
    }