【发布时间】:2020-02-24 08:00:27
【问题描述】:
我只将 angularJS(1.4) 用于前端。
我已将 JS 类 DummyClass 传递给名为 TLSService 的 angularJS-Service,并将此服务添加到名为 mLxController 的 angularJS-Controller 中。
我在从mLxController 访问DummyClass 的变量和方法时遇到问题。
例如,正如您将在下面的代码中看到的,我无法检索类变量 String。
我使用window.alert(String) 来检查。
窗口中显示的不是来自DummyClass 的字符串,而是“未定义”。
我觉得值得一提的是,当在DummyClass的constructor中添加window.alert("DummyClass calls.")时,alert会在加载相应的URL后立即显示。
这是mLxController.js的代码:
angular.module('mApp')
.controller('mLxController', function('TLSService', $scope, $state, $stateParams){
...
//this function is called in `index.html`
$scope.callTLSService = function(){
window.alert(TLSService.response);
}
...
});
这是dummyClass.js 的代码:
class DummyClass {
constructor() {
this.response = "Hi Controller! Service told me you were looking for me.";
}
}
这里是tlsService.js:
angular.module('mApp').service('TestClaServScript', function(){new DummyClass()});
更新:
我已设法使DummyClass 可用于mLxController。
虽然我很确定我的解决方案不是值得推荐的做法。
基本上,我将 DummyClass 移动到与 TLSService 相同的文件中。
此外,DummyClass 和它的路径不再在主 index.html 中提及。
因此,tlsService.js 现在看起来像这样:
angular.module('mApp').service('TestClaServScript', function(){
this.clConnect = function(inStr){
var mDummy = new DummyClass(inStr);
return mDummy;
}
});
class DummyClass {
constructor(inStr){
this.inStr = inStr;
this.response =
"DummyClass says: \"Hi Controller! Service told me you were looking for me.\"";
this.charCount = function(inStr){
var nResult = inStr.length;
var stRes = "btw, your String has "
+(nResult-1)+", "+nResult+", or "+(nResult+1)+" characters.\nIDK."
return stRes;
}
}
}
和mLxController.js:
angular.module('mApp')
.controller('mLxController', function('TLSService',$scope,$state, $stateParams){
...
$scope.makeDummyCount = function(){
var mDummy = TestClaServScript.clConnect("This string is for counting");
window.alert(mDummy.charCount(mDummy.inStr));
}
...
});
必须有一种方法可以正确导入DummyClass,以便我可以保留单独的文件。
我会做更多的研究,我会继续努力。
更新 2:问题已解决
为我的问题提供的答案帮助我按照最初计划的方式实现了TLSService。
我想在这里发布代码的最终版本,希望它可以帮助一些像我一样的初学者。
tlsService.js:
angular.module('mApp').service('TLSService', function(){
this.mCwParam = function(inputStr){
return new DummyClass(inputStr);
}
});
DummyClass 与我在第一次更新中发布的一样,但它有自己的文件 dummyClass.js,再次。
mLxController.js:
angular.module('mApp')
.controller('mLxController', function('TLSService', $scope, $state, $stateParams){
...
//this function is called in the mLx-view's `index.html`
$scope.askDummyCount = function(){
var mService = TLSService.mCwParam("String, string, string, and all the devs that sing.");
window.alert(mService.charCount());
}
...
});
另外,TLSService 和 DummyClass 已添加到应用程序主 index.html。
【问题讨论】:
-
我认为问题在于,angularJS v.1.4.x 中没有提供通过服务使用单独的类。
标签: javascript angularjs angularjs-service