首页 > 解决方案 > 在服务中注册一个回调函数,当服务使用 TypeScript 在 AngularJs 中触发回调时调用该函数

问题描述

我如何注册/订阅callback method从一个AngularJs controller到一个AngularJs service

我想在我的服务中运行的“加载程序”达到 100%$scope.property时设置一个值。

我想从 my 中返回一个, Booleanoftrue到my 。controllerservice

我想到了以下内容:在 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 =[];

对你的帮助表示感谢!

标签: angularjstypescript

解决方案


在我的服务中,我有以下代码:

在服务中:

// 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;
    });
}

推荐阅读