I'm new to services, factories, etc; so there's still a lot I don't understand.
I have a ui-grid. When a row is selected, I want to use that data as a param in a service to get REST data to populate another grid.
This is what I think it should be doing:
gridOne is registered => Row Selected => Send selectedRow.id to Service => Service GETs data => data populates grid 2
This is what its actually doing:
Service GETs data => Error because selectedRow.id is not defined.
01| $scope.gridOne.onRegisterApi = function(gridApi){
02| $scope.gridOneApi = gridApi
03| $scope.gridOneApi.selection.on.rowSelectionChanged(null, function(row){
04| $scope.gridOneSelectedRow = $scope.gridOneApi.selection.getSelectedRows()[0]
05|
06| // v---Breakpoint on this line triggered before any grid is built---v
07| myService.getAllObjects($scope.gridOneSelectedRow.id).then(response => {
08| $scope.grid2.data = response
09| }
10| })
11| }
My service looks like this:
app.service('myService', function ($http) {
return {
get: getObjects
}
function getOjects(id) {
let url = `http://${domain}/object/${id}`
return $http.get(url).then(response => {
return response
}).catch(error => {
return error
})
}
}
Why is the service function running before everything else?
if you are writing a service, you should not return a object/function/something, your implementation function is used as a constructor to newed up and create instance of your service.
so if you want to use a service, a sample for your myService will be
app.service('myService', function ($http) {
function getOjects(id) {
//you should properly replace your domain, may be with the same domain by default if you start from object/...
let url = `http://${domain}/object/+ id`
return $http.get(url).then(response => {
return response.data
}).catch(error => {
return error
})
}
this.getAllObjects = getOjects;
})
in case of factory
app.factory('myService', function ($http) {
function getOjects(id) {
//you should properly replace your domain, may be with the same domain by default if you start from object/...
let url = `http://${domain}/object/+ id`
return $http.get(url).then(response => {
return response.data
}).catch(error => {
return error
})
}
return {getAllObjects: getOjects};
})
and in the injecting end you don't need to change the code the way you are using it to load data, just wrote the code in sync of use
and also, I wnder, why you are trying to select before the data is loaded, and inside the handler of row selection you want to call the data when now row is present at all, if the data is not loaded, right? I hope you are loading data for another grid grid2 on selection of a row of grid1, and then want to load corresponding data related to that row to grid2.
Feel free to comment, whatever doubt you still have.
Good Luck :)
Related
I'm new to NodeJS and are only familiar with Java. I'm trying to create a file that creates objects based on a database and adds them to an array. This array I want to be able to export so that I can use it throughout the whole program, but when I try to export the array it doesn't work. I've tried googling and understanding but haven't come across anything that was helpful unfortunately.
I hope that someone can help me understand
I've tried calling module.exports after the ".then" call, but it just returns an empty array because its async.
I've also tried calling module.exports = teams inside the .then call but it didn't work neither.
var teams = [];
function assignTeamsToClasses() {
return new Promise((resolve, reject) => {
getAllTeamsInDb((teamList) => {
teamList.forEach((aTeam) => {
let newTeam = new Team(aTeam['teamid'], aTeam['teamname'], aTeam['teamrank']);
teams.push(newTeam);
});
resolve();
});
})
}
assignTeamsToClasses().then(() => {
module.exports = teams;
});
main.js
var teams = require('./initialize.js');
console.log(teams);
I expect it to return all teams that are in the database. I know that array is not empty when called within the ".then" call, but the export part does not.
Simple
the sequence require() + console.log() is synchronous
assignTeamsToClasses() is asynchronous, i.e. it updates teams at some unknown later point in time.
You'll have to design your module API to be asynchronous, e.g. by providing event listener interface or Promise interface that clients can subscribe to, to receive the "database update complete" event.
A proposal:
module.exports = {
completed: new Promise(resolve =>
getAllTeamsInDb(teams => {
const result = [];
teams.each(aTeam =>
result.append(new Team(aTeam.teamid,
aTeam.teamname,
aTeam.teamrank)
)
);
resolve(result);
})
),
};
How to use it:
const dbAPI = require('./initialize.js');
dbAPI
.completed
.then(teams => console.log(teams))
.catch(error => /* handle DB error here? */);
Every caller who uses this API will
either be blocked until the database access has been completed, or
receive result from the already resolved promise and proceed with its then() callback.
I'm doing an Ionic project and I'm getting a little bit frustrated whit promises and '.then()' although I've read a lot of documentation everywhere.
The case is that I have one provider with the functions loadClients and getWaybills.
The first one gets all the clients that have waybills and the second one gets all the waybills from one concrete client.
loadClients() {
return new Promise(resolve => {
this.http.get('http://localhost/waybills?fields=descr1_sped&idUser='+ this.id)
.map(res => res)
.subscribe(data => {
this.data = data.json();
resolve(this.data);
});
});
}
// GET WAYBILLS
getWaybills(client) {
return new Promise(resolve => {
this.http.get('http://localhost/waybills/?stato=0&idUser='+ this.id +'&descr1_sped='+ client)
.map(res => res)
.subscribe(data => {
this.data = data.json();
resolve(this.data);
});
});
}
On the other hand, on the component welcome.ts I have a function loadWaybills which is called on the view load and is executing the following code, my idea is to get all the clients and then get the respective waybills of each one. Then I'll take just of the ones that are defined.
The problem is that on the second .then() instead of getting the variable data I'm getting just undefined... I've understood that if you put a synchronous code inside .then() can be properly executed and work with the "data" which is the result of the promise. Why am I getting this undefined?
loadWaybills() {
//We first load the clients
this.waybills.loadClients()
.then(data => {
this.waybill = data;
var preClients = this.waybill;
this.clients = [];
//Here we're deleting duplicated clients and getWaybills of them)
for (let i = 0; i < preClients.length; i++) {
if (this.clients.indexOf(preClients[i].descr1_sped) == -1) {
this.waybills.getWaybills(preClients[i].descr1_sped)
.then(data => {
**//Here we'll check if the clients has waybills or not**
this.clientWaybills[i] = data;
this.clients.push(preClients[i].descr1_sped)
});
}
}
});
}
It is hard to say because we don't know what the API is meant to return. For example, there may be a missing field somewhere from the first GET and now for the second one, it returns as undefined sometimes. If it only returns undefined sometimes, a simple solution to this, would be to check that the value is defined before assigning it to the variable.
If it always returns as undefined and shouldn't, try to debug the code and make sure that the values are present before the second .then.
I'm learning NativeScript/Angular 2 and would need to get help with this issue.
In order to implement a multi-role login system within the Firebase platform I thought about this solution
Login the user through Firebase authentication
Query the /stores/ path for a store which has a merchantEmail field same as the e-mail that has just logged in
If I find it, I set the store ID inside a BackendService service which uses getString/setString to store tokens, then route to a MerchantDashboardComponent
If I don't find it, just route to a BuyerDashboardComponent
This is part of my code in the login.service:
login (email: string, password: string) {
return firebase.login({
type: firebase.LoginType.PASSWORD,
email: email,
password: password
}).then(
(result: any) => {
firebase.query(
(_result) => { // Here I set BackendService.storeID
Inside the .query() callback I am assigning the tokens I need in the application.
This is the method I'm using in my login.component:
doLogin () {
this.isAuthenticating = true;
if (!this.validateEmail()) {
alert("Please insert a valid email");
return false;
}
this.loginService.login(this.email, this.password).then(
() => {
this.isAuthenticating = false;
if (BackendService.loginError)
alert(BackendService.loginError)
else if (BackendService.storeID != '') {
this.router.navigate(['/merchant-dashboard'], {clearHistory: true});
}
else {
this.router.navigate(['/home/categories'], {clearHistory: true});
}
}
);
}
Everything works except for the fact that the Merchant gets routed to the Buyer dashboard. I've managed to discover that the execution order is not what I expected to be, in fact:
firebase.login() gets executed and returns a Promise
.then() handler is executed inside the doLogin() method
Only after this, the firebase.query() method completes the callback and my tokens are available, but doLogin() has already navigated the user because storeID is still empty when I need it
I hope I've been clear as much as possible.
Thanks for your attention.
Greetings,
Davide
So, the problem was in the login service method.
I now return the Promise generated by firebase.query(), which causes then() calls to chain in the correct order.
Yep that was exactly was I was going to propose to wrap it in a promise and create a chain.
example code
return new Promise<any>((resolve, reject) => {
firebase.login({ loginArguments })
.then((result: any) => {
var onQueryEvent = function (result) {
};
return firebase.query(
onQueryEvent,
"/owner",
{
// query arguments follows here
}
).then(res => {
return res;
})
})
.then(finalResult => {
console.log(finalResult);
try {
resolve(finalResult);
} catch (e) {
reject(e);
}
})
});
I'm using angular and firebase together and I have a products array which i'm storing in my rootscope, though it takes time to load the items.
My issues is that when I go to this page for example directly:
http://localhost/product/greyish-sports-shoes
If I go to the home page, the products load after 2 seconds.. and then only if I click on the product link it takes me to it, and it'll work because products have already been loaded.
It goes to the shoeService which contains the products array, but the items are still not loaded, so it cannot find the product by its slug.
That's the code I use in my run method.
var ref = firebase.database().ref().child('products');
$rootScope.shopProds = $firebaseArray(ref);
My shoeService factory:
function shoeFactory($rootScope) {
this.service = {};
this.service.store = new Store($rootScope.shopProds);
this.service.cart = new Cart();
return this.service;
}
It is important to realize that the $firebaseArray service returns an array that is initially empty. The array is populated asynchronously after the data is returned from the server.
Use the promise returned by the $loaded method attached to the array:
function shoeFactory($rootScope) {
this.service = {};
this.service.storePromise = $rootScope.shopProds.$loaded()
.then ( (shopProds) => {
return new Store(shopProds);
});
this.service.cartPromise = this.service.storePromise
.then ( () => {
return new Cart();
}).catch( (error) => {
console.log("ERROR in shoeFactory");
throw error;
});
return this.service;
}
To avoid race conditions, the code needs to use promises to chain operations.
I am trying to do something like the following:
In my controller I have functions that use $recource call to get data from database. The service 'myService'
var fillSubData = function (containerToFill) {
resService.getSubDataFromDB(//$resource service
{params},
function (res) {
//do something with containerToFill with the result res add new values
}
);
}
var fillData = function (containerToFill) {
resService.getDataFromDB(//$resource service
{params},
function (res) {
//do something with containerToFill with the result res
fillSubData(containerToFill);
}
);
}
Controller
$scope.dataToFill;// object
var initialize = function () {
//by reference
myService.fillData(dataToFill);
// I need the dataToFill filled to do other thing with data recovered and built
angular.forEach(dataToFill.someArrayBuilt, function (item) {
//do something with item...
})
}
I need the dataToFill filled to do other thing with data recovered and built, but the resource calls are asyn, how can I do this?
Note that the resource actions return an object that contains a $promise property. You can use this to proceed with a callback once the async call has returned:
myService.fillData(dataToFill).$promise.then(function() {
// I need the dataToFill filled to do other thing with data recovered and built
angular.forEach(dataToFill.someArrayBuilt, function (item) {
//do something with item...
})
});
To enable this, I suggest that you simply have your fillData method return the result of the resource call:
var fillData = function (containerToFill) {
return resService.getDataFromDB(//$resource service ...