我仅将angularJS(1.4)用于前端。
[我已将JS类DummyClass
传递给名为TLSService
的angularJS-Service,并将此服务添加到名为mLxController
的angularJS-Controller中。
我在从DummyClass
访问mLxController
的变量和方法时遇到问题。例如,您将在下面的代码中看到,我无法检索类变量String。我用window.alert(String)
检查一下。代替DummyClass
中的字符串,在窗口中显示'undefined'。
[我认为值得一提的是,当在window.alert("DummyClass calls.")
的constructor
中添加DummyClass
时,在加载相应的URL后将立即显示alert
。
这是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()});
UPDATE:
我设法使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
。
原始设置中的问题是,当您将类注册为服务时,您没有返回该类的实例:
function(){new DummyClass()}
应该是:
function(){return new DummyClass()}
仅在不使用花括号时自动返回才有效,例如
() => new DummyClass()