我的代码如下所示:
app.factory('utilityService', [
'$http',
'$angularCacheFactory',
utilityService
]);
function utilityService(
$http,
$angularCacheFactory
) {
var factory: {
rowClicked($index, collection);
} = <any>{};
factory.rowClicked = function ($index, collection) {
var row = collection[$index];
if (row.current) {
row.current = false;
return null;
} else {
collection.forEach(function (object) {
object.current = false;
});
row.current = true;
return $index;
}
};
return factory;
}
有没有办法可以将定义和代码结合起来:
var factory2: {
rowClicked: ($index, collection) => { ... };
}
return factory2;
请注意,我确实尝试了上面的代码,但我认为我没有走上正确的轨道,因为我看到了很多打字稿相关的错误。
答案 0 :(得分:1)
您可以为服务定义接口,并将其保留在服务的外部。所以你可以总结为: -
export interface IUtilityService {
/**
* Returns ...
* @param {number} $index - ...
* @param {SomeType[]} collection:SomeType - ...
* @returns {SomeType}
*/
rowClicked($index:number, collection:SomeType[]):number
}
Class UtilityService implements IUtilityService {
static $inject = [
'$http',
'$angularCacheFactory'
];
constructor(private $http : ng.IHttpService,
private $angularCacheFactory :ng.ICacheFactoryService) {
}
rowClicked($index, collection) {
var row = collection[$index];
if (row.current) {
row.current = false;
return null;
} else {
collection.forEach(function (object) {
object.current = false;
});
row.current = true;
return $index;
}
};
}
app.service('utilityService',UtilityService);
当您使用它时,您可以在其中指定依赖项的类型为IUtilityService