微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有一个项目,我将成功的Http Get请求从TypeScript(Angular HTTP Service)代码发送到Web API控制器并在网格中显示列表.该项目成功使用了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不断给我构建错误.任何帮助或解决方案将受到高度赞赏.

解决方法:

只要您使用正确的角度输入文件,您就应该能够添加标头作为配置的一部分,第二个参数类型为ng.IRequestShortcutConfig,它是具有header属性的IHttpProviderDefaults的扩展.

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐