簡體   English   中英

在等待$ onInit回調完成時,我為Angular binded屬性返回什么?

[英]What do I return for an Angular binded property while waiting for $onInit callbacks to complete

我有一個角度服務,如:

appModule.factory('dataService', DataService);

DataService.$inject = ['dataContext'];

function DataService(dataContext) {
    var service = Object.create(DataService.prototype);
    service._dataContext = dataContext;
    service._details = {};
    service.$onInit();

    return service;
}

DataService.prototype = {
    $onInit: function () {
        this._dataContext.combinedQuery(DataQuery)
            .then(function (data) {
                this._details = data[0];
            }.bind(this));
    },

    Details: function () {
        return this._details;
    }    
};

使用它的控制器如下:

DetailsController.$inject = ["dataService"];

function DetailsController(dataService) {
    this._dataService = dataService;
}

DetailsController.prototype = {
    $onInit: function () {
        this.details = this._dataService.Details;
    },

}

View正在綁定{{$DetailsController.details}}

當運行DataService.$onInit將返回時, DataService.Details函數返回值將被綁定到DetailsController.details之前this._details = data[0]已被調用。

我應該從DataService.Details返回什么,以便一旦設置this._details ,數據就會顯示在綁定視圖上?

我認為它應該像下面這樣,但我不想再次調用$onInit

return this.$onInit()
        .then(function () {
            return this._details;
        }.bind(this));

我會嘗試使用Promises

appModule.factory('dataService', DataService);

DataService.$inject = ['dataContext'];

function DataService(dataContext) {
    DataService.prototype().then( function (err, prototype){
      if(err){
       return err;
      }
       //Else
       var service = Object.create(prototype);
       service._dataContext = dataContext;
       service._details = {};
       service.$onInit();
       if(service){
         return service;
       }
    });
}

DataService.prototype = {
  return new Promise( function( resolve, reject){
    $onInit: function () {
        this._dataContext.combinedQuery(DataQuery)
            .then(function (data) {
                this._details = data[0];
            }.bind(this));
    }

    if( this.details ){
      Details: function () {
        return resolve( this._details );
      }   
    } else {
        return reject({err: 'Unable to set details'})
    }

  });  
};

我不能保證上面的代碼是否100%工作,因為我沒有構建一個Plunker或類似的東西,但它看起來真的是一個asynchronous問題。 如果這不起作用,你應該將$on.init()包裝到Promise

無論如何,我從來沒有見過像你這樣寫services/factories ,所以我對它有點困惑。

希望它有點幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM