How to Call Pagemethod in Angular js Service - asp.net

i am new in Angular js.
Static Method in Code Behind
[WebMethod]
public static string GetPracticeLocations()
{
return "[{ id: 1, name: Test AccountName}]";
}
Angular JS Service
appSettings.service('PracticeLocationsService', function () {
this.getPracticeLocations = function () {
var PracticeLocationsData = PageMethods.GetPracticeLocations();
return PracticeLocationsData;
};
});
i want to know how to implement page method in Angular JS.
Any helpful suggustein apricited
Thanks

Probably I'm too late, but you could use defer to call a page method and return a promise,
var getPracticeLocations = function () {
var deferred = $q.defer();
PageMethods.GetPracticeLocations(function (response) {
if (response) {
deferred.resolve({ result: angular.fromJson(response) });
} else {
deferred.resolve({ result: null });
}
},
function (msg, code) {
deferred.reject(msg);
});
return deferred.promise;
};

You want to look at factory() and $http
pseudo code:
angular.factory("PageMethods", ["$http", function($http){
return {
GetPracticeLocations : function(){
return $http.get("/someurl");
}
}
}]);

Related

Retrive data at real time after specific time interval by SignalR

I have page which contains three panels for employee attendence, salary, production. I have to update the panels at real time by SignalR.
My hub class
public class MessagesHub : Hub
{
private string ConnectionString = ConfigurationManager.ConnectionStrings["database"].ToString();
[HubMethodName("sendMessages")]
public void SendMessages()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessagesHub>();
context.Clients.All.updateMessages();
}
}
In Controller
public ActionResult Panels()
{
...code..
return Partial("_panelData", model);
}
The partial page has the panels along with data to display.
In the main View page(Panels), at script tag
<script>
$(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.messagesHub;
//debugger;
// Create a function that the hub can call to broadcast messages.
notifications.client.updateMessages = function () {
getData()
};
// Start the connection.
$.connection.hub.start().done(function () {
getData();
}).fail(function (e) {
alert(e);
});
});
function getData() {
$.ajax({
url: '/PanelController/Panels',
type: 'GET',
dataType: 'html'
}).success(function (result) {
$('.panel').html(result)
}).error(function () {
window.console.log("failure");
});
}
</script>
It works fine when the page loads. But i also want it to load the data at every 1 min time interval.
Thanks in advance
Maybe I missunderstood but for me SignalR is useless there. Something like this should work :
$(function() {
getData();
});
function getData() {
$.ajax({
url: '/PanelController/Panels',
type: 'GET',
dataType: 'html'
}).success(function(result) {
$('.panel').html(result)
window.setTimeout(getData(), 60000)
}).error(function() {
window.console.log("failure");
});
}
If you want to keep signalr the only things to do is to add this:
window.setTimeout(getData(), 60000) inside the callback of the getData function()

How come this isn't working Sync/Async issues with Meteor.methods

This is weird but when I call a external function from Meteor.method function it will always return undefined in the client I tried Meteor.wrapAsync but I think I'm doing something wrong. Here is my code:
var demoFunction = function () {
//database operations
var user = this.userId;
if (!user)
return;
var count = Users.aggregate([
{ $group: {_id: null, count: {$sum: 1}} }
]);
if (count[0] && count[0].count)
return count[0].count;
return 0;
}
Meteor.methods({
// NOT WORKING, How can I make this work?
methodDemo: function () {
var result = demoFunction ();
return result;
},
// Works
methodDemo2: function () {
//database operations
var user = this.userId;
if (!user)
return;
var count = Users.aggregate([
{ $group: {_id: null, count: {$sum: 1}} }
]);
if (count[0] && count[0].count)
return count[0].count;
return 0;
}
});
// Call from client
Meteor.call("methodDemo", function (err, res) { });
calling external functions doesn't work the same way if I put the code inside the meteor method why?
Try using Meteor.userId() in your function instead of this.userId. I think you are loosing the value of this when calling your function causing it to exit early.
Since you declared the function with a var it is scoped outside of methodDemo().
You could declare the function globally by removing var or move the demoFunction() code into methodDemo().

Meteor External API calls works but client gets Undefined

Client Side:
Template.storeInfo.events({
'click #btn-user-data': function(e) {
Meteor.call('callApi', function(err, data) {
$('#result').text(JSON.stringify(data, undefined, 4));
console.log(data); //Not working!!
});
}
});
Server Side:
storeApi.prototype.retrieve = function(endpoint) {
try {
var gotiye = HTTP.get(endpoint);
console.log(gotiye); //Works!
return gotiye;
} catch (err) {
throw new Error("Failed to fetch call GET retrieve from store. " + err.message);
}
};
storeApi.prototype.getStoreInfo = function() {
var url = this.rootApiUrl.replace(this.endpointToken,
this.endpoints.store);
this.retrieve(url);
};
Meteor.methods({
callApi: function() {
var stnvy = new storeApi(Meteor.user().services.store.accessToken);
var data = stnvy.getStoreInfo();
return data;
}
});
Why it works on server side but impossible to use in client side? Is collection the only way to use this?
Forgot to return it at getStoreInfo function return this.retrieve(url); and it works! :)

Multiple Data Contexts in router - Meteor

I'm building a meteor app and on one route I'm adding multiple data context like so -
this.route('orgPage', {
path: '/org/:title',
data: {
orgs: function () {Orgs.findOne(this.params._id)},
projects: function() {Meteor.subscribe('projects', this.params._id)}
}
The only problem is that when I try to access this data in my templates js file, I can't access the _id or any of the attributes of orgs.
I've tried several approaches, but it always returns undefined. If I use a single data context, it works perfectly. Here is the function that doesn't function properly -
Template.orgPage.events({
'click #newProject': function(e) {
$('#npModal').modal();
},
'submit #npModal form': function(e, template) {
e.preventDefault();
if(!$(e.target).find('[name=newTitle]').val()) {
var projectTitle = 'Untitled'
} else {
var projectTitle = $(e.target).find('[name=newTitle]').val()
}
var theid = this._id;
var newProject = {
title: projectTitle,
organization: theid
}
Meteor.call('project', newProject, function(error, id) {
if (error)
return alert(error.reason);
$('#npModal').modal('hide');
$('#npModal').on('hidden.bs.modal', function (e) {
Router.go('newFields', {});
})
});
});
Anyone have any ideas? Thanks!!
You have missed a return statement. function () {Orgs.findOne(this.params._id)} should be function () {return Orgs.findOne(this.params._id)}. Further more, this inside this function won't refer to what you want, so you can't use this.params. And why do you subscribe to a subscription as a data context property? Do it in the waitOn function instead.

this.get_element() of asp.net ajax is not working in functions I declare

I try to access the element in my own function through this.get_element() but it does not work.
Type.registerNamespace("LabelTimeExtender1");
LabelTimeExtender1.ClientBehavior1 = function(element) {
LabelTimeExtender1.ClientBehavior1.initializeBase(this, [element]);
var testelement=this.get_element();
var timestamp= this.get_element().attributes['TimeStamp'].value;
alert("in constructor");
},
LabelTimeExtender1.ClientBehavior1.prototype = {
initialize: function() {
LabelTimeExtender1.ClientBehavior1.callBaseMethod(this, 'initialize');
setInterval (this.timer,1000);
alert("after");
},
dispose: function() {
//Add custom dispose actions here
LabelTimeExtender1.ClientBehavior1.callBaseMethod(this, 'dispose');
},
timer: function(){
debugger;
var date= new Date(this.timestamp);
var datenow= new Date ();
this._element.innerText=" ";
if(date.getUTCFullYear<datenow.getUTCFullYear)
{
var myelement= this.get_element();
myelement .innerHTML= date.getUTCFullYear.toString();
}
if(date.getUTCMonth<datenow.getUTCMonth)
{
this.get_element().innerHTML=date.getUTCMonth.toString();
}
if(date.getUTCDay<datenow.getUTCDay)
{
this.get_element().innerHTML=date.getUTCDay.toString();
}
if(date.getUTCHours <datenow.getUTCHours )
{
this.get_element().innerHTML=date.getUTCHours .toString();
}
if(date.getUTCMinutes<datenow.getUTCMinutes)
{
this.get_element().innerHTML=date.getUTCMinutes.toString();
}
}
}
LabelTimeExtender1.ClientBehavior1.registerClass('LabelTimeExtender1.ClientBehavior1', Sys.UI.Behavior);
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
Here I am trying to access the custom attribute 'TimeStamp' and calcutate the time and assign to the label to show.
Try to invoke your function through delegates.Then you will not have problem with [this] keyword
something like this:
setInterval (Function.createDelegate(this, this.timer),1000)

Resources