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

3
我有一个项目,其中我成功地通过 TypeScript (Angular HTTP 服务) 代码向 Web API 控制器发出 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请求调用添加一个自定义标头。 我尝试了很多方法,但是TypeScript一直给我构建错误。任何帮助或解决方法都将不胜感激。


1
你收到了什么错误信息? - MartyIX
构建错误。接口的任何方法或属性都不接受标头值。 - Foyzul Karim
1个回答

6
只要您使用正确的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.
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接