Зарегистрируйте функцию обратного вызова в службе, которая вызывается, когда служба вызывает обратный вызов в AngularJs с помощью TypeScript - PullRequest
0 голосов
/ 23 мая 2018

Как я могу зарегистрироваться / подписаться на callback method от AngularJs controller до AngularJs service?

Я хочу установить значение $scope.property, когда мой ' загрузчик ', работающий в моем сервисе, достиг 100%.

Я хочу вернуть Boolean, true моему controller из моего service.

Я имел в виду что-то вроде следующего: Создать method в моем controller, который регистрируется в моем service, который вызывается, когда мой загрузчик достиг 100%по моему 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 =[];

Ваша помощь будет высоко оценена!

1 Ответ

0 голосов
/ 29 мая 2018

В моем сервисе у меня есть следующий код:

В сервисе:

// 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;
    });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...