我需要能够在同一模块中的控制器中更改Angularjs服务中的变量值。 TL; DR版本低于...如何从控制器动态更改Angularjs服务内部的变量值?
我有一个嵌入式系统,带有一个由Swagger文件描述的RESTful API。我通过Angularjs应用程序访问它。为了创建这个应用程序,我使用了swagger-codegen来自动生成服务。这会导致一个服务传递一个基本路径,该基础路径在服务内部从$ http调用中使用。该服务是这样的:
API.Client.MyApi = function($http, $httpParamSerializer, $injector) {
/** @private {!string} */
this.basePath_ = $injector.has('MyApiBasePath') ?
/** @type {!string} */ ($injector.get('MyApiBasePath')) :
'http://localhost/';
...
}
在我的角度app.js文件,我有以下几点:
var myApp = angular.module('MyApp', [
])
.service('MyApi', API.Client.MyApi)
.value('MyApiBasePath', 'http://192.168.1.128');
这一切运作良好。但是,我希望能够从应用程序内设置设备的基本路径(特别是IP地址)。但是服务是从一开始就开始的,我不知道如何让控制器能够更新服务变量basePath_。
我可以重写服务函数来接受basepath作为参数,但我不想重写由swagger-codegen自动生成的服务。
我对任何解决方案都很开放 - 寻找什么可能是最好的方法来做到这一点。
更新:2016/5/24 - 有人让我发表招摇的代码。这里是文件,包括初始服务功能以及方法之一的相关部分...
API.Client.MyApi = function($http, $httpParamSerializer, $injector) {
/** @private {!string} */
this.basePath_ = $injector.has('MyApiBasePath') ?
/** @type {!string} */ ($injector.get('MyApiBasePath')) :
'http://localhost/';
/** @private {!Object<string, string>} */
this.defaultHeaders_ = $injector.has('MyApiDefaultHeaders') ?
/** @type {!Object<string, string>} */ (
$injector.get('MyApiDefaultHeaders')) :
{};
/** @private {!angular.$http} */
this.http_ = $http;
/** @private {!Object} */
this.httpParamSerializer_ = $injector.get('$httpParamSerializer');
}
API.Client.MyApi.$inject = ['$http', '$httpParamSerializer', '$injector'];
/**
* Thingy Outputs
* Returns the state of all thingys
* @param {!angular.$http.Config=} opt_extraHttpRequestParams Extra HTTP parameters to send.
* @return {!angular.$q.Promise<!Array<!API.Client.boolGetModel>>}
*/
API.Client.MyApi.prototype.thingyGet = function(opt_extraHttpRequestParams) {
/** @const {string} */
var path = this.basePath_ + '/thingys';
/** @type {!Object} */
var queryParameters = {};
/** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders);
/** @type {!Object} */
var httpRequestParams = {
method: 'GET',
url: path,
json: true,
params: queryParameters,
headers: headerParams
};
if (opt_extraHttpRequestParams) {
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
}
return this.http_(httpRequestParams);
}
的“规定“方法(通过swagger的例子)我上面描述(与.service/.value作为角模块声明的一部分。当我尝试你推荐的东西 - var myserviceobj = new API.Client.MyApi,我得到: ”API .Client.MyApi不是构造函数。“ – user5890478
你可以在这里发布swagger-codegen生成的所有文件吗? –
我编辑了上面的代码以显示swagger-codegen文件。 – user5890478