angularjs - 在服务中注册一个回调函数,当服务使用 TypeScript 在 AngularJs 中触发回调时调用该函数
问题描述
我如何注册/订阅callback method
从一个AngularJs
controller
到一个AngularJs
service
?
我想在我的服务中运行的“加载程序”达到 100%$scope.property
时设置一个值。
我想从 my 中返回一个, Boolean
oftrue
到my 。controller
service
我想到了以下内容:在 my 中
创建一个method
在 mycontroller
中注册的service
,当我的加载程序在我的service
. 我只是不确定我是否走在正确的轨道上,以及如何填补缺失的部分。
控制器:
this._scope.loaderHasLoaded = this._progressBarService.loaderHasCompleted.push(function done(): boolean{})
服务:
public loadingComplete():boolean{
if (this.isLoaderLoaded === true) {
return true
} else {
return false;
}
}
// some missing functionality
public loaderHasCompleted =[];
对你的帮助表示感谢!
解决方案
在我的服务中,我有以下代码:
在服务中:
// declare an array that will hold all my callback functions to be called after the loader has completed
private _callbacks = [];
// The method that will be called from the Controller to push the callback method into the _callbacks array
public listenLoadedComplete(callback: Function) {
this._callbacks.push(callback);
}
// In the actual loader method set the isLoaded variable to true and call the loadingComplete method
this.isLoaderLoaded = true;
this.loadingComplete();
// The loadingCompleted method executes each registered method in the _callback array
public loadingComplete(): boolean {
if (this.isLoaderLoaded === true) {
for (let cb of this._callbacks) {
cb();
}
return true
} else {
return false;
}
}
在控制器中:
// Call the listenForLoadCompletion method
this.listenForLoadCompletion();
// Register the callback function in the _callback array in the Service
// After the service has completed and called the method loadingComplete, the callback will be called
public listenForLoadCompletion(): void {
this._progressBarService.listenLoadedComplete(() => {
this._scope.loaderHasLoaded = true;
});
}
推荐阅读
- javascript - 嵌套的 TouchableOpacity Parent onPress 不起作用
- python - 我正在尝试将 celery 应用于 django 中基于类的视图(apis)。我怎样才能做到这一点?
- javascript - 用 css 覆盖 img - 来自不同设备的可视化问题
- python - 如何在嵌套 for 循环下对我的嵌套 if 语句进行矢量化(使用 Numpy/Pandas)
- spring-boot - SpringBoot,测试容器以测试发送到外部数据库的查询
- sparql - 嵌套 SPARQL 查询
- c# - 通过 PowerShell 管理 .Net 可执行文件的引用
- php - 为什么用户输入不附加到我的 SQL 数据库?
- websocket - 如何在 JMeter 的 While 控制器中过滤掉最后一个采样器?
- javascript - 回调函数未定义,即使它在调用 javascript 之前已被定义