javascript - Angular JS TypeScript IHttpService แทรกค่าหัวข้อกำหนดเอง
ฉันมีโปรเจกต์ที่ฉันทำการร้องขอ Http Get สำเร็จ จาก TypeScript (บริการ HTTP ของ Angular) ไปยัง Web API controller และแสดงรายการในกริด โปรเจกต์ใช้ Angular JS 1.4.x และ TypeScript อย่างสำเร็จ
URL GitHub ของโครงการทั้งหมด และโค้ด 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 request ฉันได้ลองหลายวิธีแล้ว แต่ TypeScript ยังคงแจ้งข้อผิดพลาดในการสร้างใด ๆ ความช่วยเหลือหรือตัวแก้ปัญหาใด ๆ จะได้รับการชื่นชมอย่างมาก
คำตอบ #1
ตราบใดที่คุณกำลังใช้ไฟล์การพิมพ์ที่ถูกต้องสำหรับ Angular คุณควรจะสามารถเพิ่ม header เป็นส่วนหนึ่งของการกำหนดค่า อาร์กิวเมนต์ที่สองซึ่งมีชนิดเป็น 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.
}
}
