javascript - วิธีแทรกค่าคงที่เข้าสู่โมดูลอื่นใน angular typescript?
ใน Angular1 เรากำหนดค่าคงที่ด้วยวิธีนี้
angular.module('taskApp', [
'ui.router',
'angular-loading-bar',
'ngMessages',
])
.constant('url', {
BASE: 'http://localhost:3222',
BASE_API: 'http://localhost:3222/v1'
});
แล้วฉันก็สามารถฉีดมันเข้าไปในโมดูลใดก็ได้ที่ฉันต้องการแบบนี้,
Auth.$inject = ['$http', 'url'];
function Auth($http, url)
ตอนนี้การใช้ TypeScript ฉันอยากทำแบบเดียวกัน ฉันเคยเห็นวิธีนี้: การฉีดค่า Angular Constants ใน TypeScript ซึ่งดูเหมือนโอเค แต่ไม่ใช่วิธีที่ฉันกำลังมองหา
จากการวิจัยของฉัน
static $inject = ["$resource", "url"];
constructor(private $resource: ng.resource.IResourceService, private url: ng.IModule)
ฉันกำลังใช้ IModule เพราะมันเป็นเพียงคำใบ้เดียวจากไฟล์ tsd ของ Angular
/**
* Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator.
*
* @param name The name of the constant.
* @param value The constant value.
*/
constant(name: string, value: any): IModule;
constant(object: Object): IModule;
แต่ไม่สามารถหาคุณสมบัติที่ถูกต้องเพื่อดึงตัวแปรของฉันได้
คำตอบ #1
วิธีหนึ่งที่จะทำได้คือการกำหนดอินเทอร์เฟซที่อธิบายค่าคงที่
interface URL_CONSTANTS {
BASE: string,
BASE_API: string
}
จากนั้นคุณจะสามารถใช้สิ่งนั้นเป็นชนิดของค่าคงที่ที่ถูกฉีดเข้าไปได้
static $inject = ["$resource", "url"];
constructor(private $resource: ng.resource.IResourceService, private url: URL_CONSTANTS)
