问题
I an using Ionic for my app with a connection to Firebase to pull data. I created a promise in a factory to pull data down and thought it should render the data on the screen once it finishes but I'm getting nothing until I touch the screen?
I get no error and the data does indeed come.
Factory:
all: function () {
return new Promise ((resolve, reject) => {
firebase.database().ref('desks').once('value').then(snapshot => {
let desks = []
snapshot.forEach((child) => {
desks.push(child.val());
});
resolve(desks)
});
});
}
Calling the Factory:
Office.all().then(function (data) {
console.log(data);
$scope.officeList = data;
});
I feel I'm calling it wrong or else there is an Ionic method that I can't seem to find.
How will I be able to have the data render once it finishes the request?
Thanks in advance
回答1:
ES6 promises are not integrated with the AngularJS framework. Use $q.when to convert ES6 promises to AngularJS promises. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.
all: function () {
̶r̶e̶t̶u̶r̶n̶ ̶n̶e̶w̶ ̶P̶r̶o̶m̶i̶s̶e̶ ̶(̶(̶r̶e̶s̶o̶l̶v̶e̶,̶ ̶r̶e̶j̶e̶c̶t̶)̶ ̶=̶>̶ ̶{̶
var es6promise = firebase.database()
.ref('desks').once('value')
.then(snapshot => {
let desks = []
snapshot.forEach((child) => {
desks.push(child.val());
});
̶r̶e̶s̶o̶l̶v̶e̶(̶d̶e̶s̶k̶s̶)̶
return desks;
});
return $q.when(es6promise);
}
Also avoid using Promise(resolve,reject
to create new promises. Instead use the promise returned by the .then method. It returns a new promise which is resolved or rejected via the return value of the successCallback
, errorCallback
(unless that value is a promise, in which case it is resolved with the value which is resolved in that promise using promise chaining).
For more information, see You're Missing the Point of Promises.
来源:https://stackoverflow.com/questions/46734810/data-from-es6-promise-doesnt-render-on-the-page-until-i-click-on-it