creating service
myApp.factory('serviceHttp', ['$http', function(http) {
http.get($scope.url).then(function(result){
serviceVariable = result;
}
return serviceVariable;
}
Controller
function appController($scope, serviceHttp){
$scope.varX = serviceHttp;
if(serviceHttp){
// decision X;
} else {
// decision Y;
}
}
view:
input(ng-if='varX') serviceHttp Exist
input(ng-if='!varX') serviceHttp noExist
The above code always shows varX not exist because app installs during http call of service. I want to use angular service to inject variables from server to make decision at time of booting the application.
Try to rewrite factory by this way that returns promise:
myApp.factory('serviceHttp', ['$http', function(http) {
var factory = {
query: function () {
var data = http.get($scope.url).then(function(result){
return result;
},
function (result) {
alert("Error: No data returned");
});
return data;
}
}
return factory;
}]);
From controller:
serviceHttp.query().then(function (result) {
$scope.varX = = result;
}
Here is Demo Fiddle
in demo we used other URL source
If i correct understand you, you should doing it like this:
var app = angular.module('YourModule', []);
app.factory("serviceHttp", function($http) {
var serviceHttp={};
serviceHttp.yourGetRequest = function(yourUrl) {
return $http.get(yourUrl);
};
return serviceHttp;
});
And for example, controller:
var Controller = function($scope,serviceHttp) {
$scope.varX='';
$scope.loading = true;
var returnArr = serviceHttp.yourGetRequest($scope.url).success(function(dataFromServer) {
$scope.loading = false;
$scope.varX = dataFromServer;
})
};
in view you can use ng-show, like this:
<div ng-show="loading" class="loading"><img src="../styles/ajax-loader-large.gif"></div>
When your application start loading, $scope.loading = true and this div shown, and when you get response from server $scope.loading became false and div doesn't show.
Related
I dynamically create collections with this method:
createPlist: function(jid) {
try {
Plist[jid] = new Meteor.Collection(pid);
} catch(e) {
console.log("oops, I did it again");
}
Plist[jid].insert({
...,
...,
public:true,
uid:this.userId
});
}
Then I am wanting to publish these selectively, and I am attempting to do it via a method:
getPlist: function(jid,pid) {
// var future = new Future();
try {
Plist[jid] = new Meteor.Collection(pid);
} catch(e) {
console.log("oops, I did it again");
}
Meteor.publish(pid, function() {
console.log(Plist[jid].find({}));
// future["return"](Plist[jid].find({}));
return Plist[jid].find();
});
// return future.wait();
},
This returns 'undefined' to my Template helper, and returns nothing (i.e. waits forever) using Future.
Any user can log in and create a Plist collection, which can be either public or not. A user can also subscribe to any collection where public is true. The variable jid is passed to the method 'getPlist' from the template. It is stored in the user's Session.
Thanks! I hope I have explained it well enough!
And of course the template:
Template.plist.helpers({
getPlist: function() {
Pl = []
jid = Session.get('jid');
//alert(jid);
pid = "pl_"+jid;
// console.log(pid);
Meteor.call('getPlist', jid, pid, function(err,res) {
console.log(res); //returns undefined
try {
Pl[jid] = new Meteor.Collection(pid);
} catch(e) {
console.log(e);
}
Meteor.subscribe(pid);
// return Pl[jid].find({}).fetch();
});
}
I've been testing on http calls with meteor, I used nitrous (because I had no access to my dev laptop during the weekend) and it worked fine.
But when I tried to run from my local pc it returns:
Exception in delivering result of invoking 'getMatch': TypeError:
Cannot read property 'duration' of undefined.
Any ideas of what could be the cause?
Method definition:
Dota = {};
Dota.getMatch = function() {
if (!Meteor.settings.steamToken)
throw new Meteor.Error(500, 'Enter a valid Steam Token in Meteor.settings');
var matchResponse = Meteor.http.get(
"https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/?",
{
params:{
"match_id": "1305454585",
"key": Meteor.settings.steamToken
}
}
);
if (matchResponse.statusCode === 200) {
return matchResponse.data.result
}
else {
throw new Meteor.Error(500, "getMatch failed with error: "+matchResponse.statusCode);
}
}
Meteor.methods({
'getMatch': function(){
return Dota.getMatch();
}
})
Calling the method:
Meteor.call('getMatch', function(error, result){
var duration = numeral(result.duration).format('00:00:00');
Session.set('duration', duration);
var winner = Meteor.myFunctions.getWinner(result.radiant_win);
Session.set('winner', winner);
});
Template.layout.helpers({
winner: function () {
return Session.get('winner');
},
duration: function () {
return Session.get('duration');
}
});
Found a solution, I changed the location of
Meteor.methods({
'getMatch': function(){
return Dota.getMatch();
}
})
to server/server.js (I had it in packages/dota/dota.js) and now it works! Thanks #user3374348 for helping!
On the client I need a helper method that returns true or false depending on whether the user is eligible for a payment request.
However, I can't really use a Meteor.method for this, because they don't return a value on the client.
Instead, I have done this and would like to know if this poses any security holes or if there is a preferable approach
Server:
...
// Constants
//
_.extend(Payments, {
MINIMUM_REQUIRED_FOR_REQUEST: 100
});
// Public
//
Meteor.methods({
});
canRequestPayment = function(userId) {
var user = Meteor.users.findOne(userId, { fields: { earnings: 1 } });
if (_.isUndefined(user)) { throw new Meteor.Error('user-not-found', 'User not found'); }
return hasEnoughCreditForRequest(user) && hasNoPendingPayments(user);
};
// Private
//
var hasNoPendingPayments = function(user) {
return Payments.find({ userId: user._id, state: 'pending' }).count() === 0;
};
var hasEnoughCreditForRequest = function(user) {
var period = user.earnings.period;
return period >= Payments.MINIMUM_REQUIRED_FOR_REQUEST;
};
As can be seen, I have created two helper methods with var, to mimic private behavior, and then I have the canRequestPayment method which is accessable outside of the file, and that I call on the client instead of a Meteor.method
Client:
Template.payments.helpers({
eligibleForPaymentRequest: function() {
return canRequestPayment(Meteor.userId());
},
I am using keystone#0.2.32. I would like to change the post category to a tree structure. The below code is running well except when I create a category, it goes into a deadlock:
var keystone = require('keystone'),
Types = keystone.Field.Types;
/**
* PostCategory Model
* ==================
*/
var PostCategory = new keystone.List('PostCategory', {
autokey: { from: 'name', path: 'key', unique: true }
});
PostCategory.add({
name: { type: String, required: true },
parent: { type: Types.Relationship, ref: 'PostCategory' },
parentTree: { type: Types.Relationship, ref: 'PostCategory', many: true }
});
PostCategory.relationship({ ref: 'Post', path: 'categories' });
PostCategory.scanTree = function(item, obj, done) {
if(item.parent){
PostCategory.model.find().where('_id', item.parent).exec(function(err, cats) {
if(cats.length){
obj.parentTree.push(cats[0]);
PostCategory.scanTree(cats[0], obj, done);
}
});
}else{
done();
}
}
PostCategory.schema.pre('save', true, function (next, done) { //Parallel middleware, waiting done to be call
if (this.isModified('parent')) {
this.parentTree = [];
if(this.parent != null){
this.parentTree.push(this.parent);
PostCategory.scanTree(this, this, done);
}else
process.nextTick(done);
}else
process.nextTick(done); //here is deadlock.
next();
});
PostCategory.defaultColumns = 'name, parentTree';
PostCategory.register();
Thanks so much.
As I explained on the issue you logged on Keystone here: https://github.com/keystonejs/keystone/issues/759
This appears to be a reproducible bug in mongoose that prevents middleware from resolving when:
Parallel middleware runs that executes a query, followed by
Serial middleware runs that executes a query
Changing Keystone's autokey middleware to run in parallel mode may cause bugs in other use cases, so cannot be done. The answer is to implement your parentTree middleware in serial mode instead of parallel mode.
Also, some other things I noticed:
There is a bug in your middleware, where the first parent is added to the array twice.
The scanTree method would be better implemented as a method on the schama
You can use the findById method for a simpler parent query
The schema method looks like this:
PostCategory.schema.methods.addParents = function(target, done) {
if (this.parent) {
PostCategory.model.findById(this.parent, function(err, parent) {
if (parent) {
target.parentTree.push(parent.id);
parent.addParents(target, done);
}
});
} else {
done();
}
}
And the fixed middleware looks like this:
PostCategory.schema.pre('save', function(done) {
if (this.isModified('parent')) {
this.parentTree = [];
if (this.parent != null) {
PostCategory.scanTree(this, this, done);
} else {
process.nextTick(done);
}
} else {
process.nextTick(done);
}
});
I think it's a bug of keystone.js. I have changed schemaPlugins.js 104 line
from
this.schema.pre('save', function(next) {
to
this.schema.pre('save', true, function(next, done) {
and change from line 124 to the following,
// if has a value and is unmodified or fixed, don't update it
if ((!modified || autokey.fixed) && this.get(autokey.path)) {
process.nextTick(done);
return next();
}
var newKey = utils.slug(values.join(' ')) || this.id;
if (autokey.unique) {
r = getUniqueKey(this, newKey, done);
next();
return r;
} else {
this.set(autokey.path, newKey);
process.nextTick(done);
return next();
}
It works.
I'm trying to get some data from an API in the variable $scope.proposition with the following code
'use strict';
var app = angular.module('app', []);
app.controller('propositionCtrl',['$scope', 'propositionRepository',
function ($scope, propositionRepository) {
// $scope.proposition = { marge_propose: 3 };
function getProposition() {
propositionRepository.getProposition(function (result) {
$scope.proposition = result;
console.log("we put the json in the scope variable");
}
)
}
getProposition();
$scope.proposition = {marge_propose : 3};
}])
app.factory('propositionRepository', function ($http) {
return {
getProposition: function (callback) {
$http.get('/api/propositionapi/3');
console.log("we call the api");
}
}
})
With the following view
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div ng-controller="propositionCtrl">
<p>{{ proposition.marge_propose}}</p>
</div>
It does not work, but when I uncomment the $scope.proposition = { marge_propose: 3 }; everything works just fine.
That's why I assume that it is my getProposition that encounters some problems.
I don't know what it is because firebug actually tells me that the data are well received from the api with the following result
{"$id":"1","t_concours":{"$id":"2","t_proposition":[{"$ref":"1"}],"id":1,"intitule":"test","valeur":10.0},"t_demandeur":{"$id":"3","t_proposition":[{"$ref":"1"}],"id":"1","nom":"dylan","prenom":"bob","note":"A"},"t_index":{"$id":"4","t_proposition":[{"$ref":"1"}],"id":1,"intitule":"test","valeur":10.0},"t_proposition_concurence":null,"id":3,"id_demandeur":"1","date_proposition":"1991-07-05T00:00:00","type":true,"point_de_vente":"01","code":"a","code_sas":"846684","montant_operation_hors_frais":200,"concours_sollicite":10,"duree_concours":10,"type_concours":1,"id_index":1,"apport_personnel":10,"garantie_reelle":true,"in_fine":false,"majoration":1.0,"prospect":true,"primo_accedant":true,"motif_montant":false,"motif_contrepartie":false,"motif_depot_cmne":false,"id_prop_concurence":null,"motif_autre":true,"motif_commentaire":"true","proposition_derogatoire":true,"visa_responsable":"false","marge_grille":5.0,"marge_theorique":7.0,"marge_propose":32.0}
Can someone explain me please where the problem is?
Thanks a lot!
EDIT:
The console log displays "we call the api" but not "we put the json in the scope variable"
'use strict';
var app = angular.module('app', []);
app.controller('propositionCtrl',['$scope', 'propositionRepository',
function ($scope, propositionRepository) {
// $scope.proposition = { marge_propose: 3 };
function getProposition() {
propositionRepository.getProposition(function (result) {
console.log("we put the json in the scope variable");
$scope.proposition = result;
}
)
}
getProposition();
$scope.proposition = {marge_propose : 3};
}])
app.factory('propositionRepository', function ($http) {
return {
getProposition: function (callback) {
$http.get('/api/propositionapi/3').success(callback);
console.log("we call the api");
}
}
})
This code works...
The thing is that I didn't know that $http.get returns a promise, so I forgot to add the .success(callback) in the line
$http.get('/api/propositionapi/3').success(callback);
Now everthing works.
Thanks for the hint MohammedAbbas
You could try to set the extra data as real JSON, eg:
$scope.proposition = { "marge_propose": "3" };
maybe try to console.log in your propositionRepository to view the result you're getting, place a console.log in the getProposition() as well to check if everything is passing trough fine
EDIT:
here's a working fiddle:
http://jsfiddle.net/c1zxp6uo/
bottomline: you don't call the callback, so when you do
$http.get('/api/propositionapi/3').then(function(){callback()})
it should work