gpt4 book ai didi

javascript - AngularJS 在运行时覆盖依赖

转载 作者:搜寻专家 更新时间:2023-11-01 04:37:21 24 4
gpt4 key购买 nike

我有一个名为 $doggedHttp 的服务,它公开了与 $http 相同的接口(interface)。现在我想创建一个 $doggedResource 服务,它是 $doggedHttp 之上的 Angular $resource 服务,而不是 $http。换句话说,我想将 $doggedHttp 作为 $http 服务注入(inject)。

此外,在我的应用程序中,我希望能够创建 $doggedResource$resource。因此我不能简单地用 $doggedHttp 覆盖 $http

我认为依赖注入(inject)应该可以轻松解决这种情况。我错了吗?

相反,我不得不深入研究 Angular 源代码,最终得出了一个非常丑陋的解决方案:

angular.module('doggedResource', ['ngResource', 'doggedHttp'])
.config(function() {
var ngResource = angular.module('ngResource'),
doggedResource = angular.module('doggedResource');

// replace the placeholder below with the $resource factory from ngResource
doggedResource._invokeQueue[1][2][1][2] = ngResource._invokeQueue[0][2][1][2];
})
.factory('$doggedResource', ['$doggedHttp', '$parse', null /* this is just a placeholder */]);

有更好的解决方案吗?


请注意,我们不能使用$provide.decorator 来替换注入(inject)的$http 服务。为了说明问题,这里是 angular-resource.js 的相关部分:

angular.module('ngResource', ['ng']).
factory('$resource', ['$http', '$parse', function($http, $parse) {

function ResourceFactory(url, paramDefaults, actions) {
}

return ResourceFactory;
}

查看上面的代码,$provide.decorator 回调将作为参数传递给 ResourceFactory。那时依赖项 $http 已经解决了。由于 ResourceFactory 在闭包中使用 $http,我们无法更改它。

.config(function($provide) {
$provide.decorator( '$resource', [ "$delegate", function( $delegate ) {
// here $delegate is the ResourceFactory which has
// already been linked to `$http` by a closure.
}
}

最佳答案

您可能应该在 $http 的装饰器中编写 $doggedHttp 中的所有逻辑。一旦你装饰了 $http,一切都应该正常工作

编辑:条件更正。

.config(function($provide) {
$provide.decorator( '$http', [ "$delegate", function( $delegate ) {
// here $delegate is the $http function.
function $doggedHttp(config){
//write your storage logic here.

// route all the $http calls through $delegate at the end...
return $delegate(config);
}
//dont forget to create shortcut method overrides.
//createShortMethods('get', 'delete', 'head', 'jsonp');
//createShortMethodsWithData('post', 'put');

// This is the simplest solution to what you wish to do..
if( condition ) {
return $doggedHttp;
}
else {
return $delegate;
}

//finally return the $doggedHttp ( and not the $delegate )

}
}

或者,您可以将所有存储逻辑写入请求拦截器 - 您也可以在其中注入(inject)任何东西,因此存储调用和重新请求也可以在那个阶段完成.

关于javascript - AngularJS 在运行时覆盖依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19353515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com