Angular JS TypeScript的IHttpService注入自定义头值
Angular JS TypeScript IHttpService inject custom header value
我有一个项目,我使成功的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.
}
}
相关文章:
- 会话注入不适用于自定义类
- $injector:modulerr将自定义模块注入Angular应用程序
- 将自定义CSS注入WP Admin登录弹出iframe
- 在Angular 2中的另一个服务中注入自定义服务
- angularjs自定义模块与$http注入
- 角度 js 自定义服务/工厂无法注入控制器/配置
- 自定义提供程序 $injector:modulerr 的角度依赖注入
- 我可以将Javascript代码注入Chrome自定义选项卡吗
- 如何在angularjs的自定义服务中注入$cookie
- 使用Selenium Web驱动程序注入自定义JS代码
- 如何在纯ES5(Javascript)中向angular组件注入自定义服务
- 在AngularJS中,当自定义服务注入到不同的模块时,未知的提供商
- Angular JS TypeScript的IHttpService注入自定义头值
- “未知Provider"将自定义过滤器注入服务时
- 自定义javascript应该在哪里注入Wordpress主题?
- 在ionic项目中注入自定义JS文件
- 角.注入器——找不到自定义(与应用相关的)服务
- 使用$http注入的自定义指令
- AngularJs/ngCordova自定义构建离子注入模块错误
- 在Jasmine中对Angular进行单元测试时,将模拟自定义提供程序注入到提供程序中