In controller, i am returning object from factory. The method is callback type.
But the problem is that the object is not returing.
My implementation is as:
.factory('fileReadFactory', ['$http',
function ($http) {
var objRead = {
setReadObject: '',
setPath: 'comMyTaxi',
setFileName: '',
status: false,
errorCode: ''
};
var factory = {};
factory.fileRead = function RequestFileSystem(fileName) {
alert('factory start');
objRead.setFileName = fileName;
try {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, createDirectory, fail);
objRead.status = true;
return objRead;
} catch (e) {
return objRead;
}
}
///write steps starts
function createDirectory(fs) {
fs.root.getDirectory(objRead.setPath, {create: true, exclusive: false}, onSuccessCreateFile, fail);
}
function onSuccessCreateFile(dirEntry) {
dirEntry.getFile(objRead.setFileName + '.txt.gz', null, gotFileEntryRead, fail);
}
function gotFileEntryRead(fileEntry) {
// alert('in 2 type step2');
fileEntry.file(gotFileReading, fail);
}
function gotFileReading(file) {
// alert('in 2 type step3');
readFile(file);
}
function readFile(file) {
// alert('in 2 type step4');
var reader = new FileReader();
reader.onloadend = function (e) {
// alert("Text is: "+this.result);
objRead.setReadObject = this.result;
}
reader.readAsText(file);
// alert('reading Ends');
}
//write file ends
function fail(err) {
alert('error ' + err.code);
objRead.errorCode = err.code;
throw e;
}
return factory;
}]);
And my call inside controller is like
var objReturn = fileReadFactory.fileRead('myProfile');
alert(objReturn.status);
alert(JSON.parse(objReturn.setReadObject));
if(objReturn.status){
var obj= JSON.parse(objReturn.setReadObject);
// alert(obj);
// alert('Inside Object World');
$scope.myprofile = obj;
}
I am not getting the if block. So how do i manage the call back;
Try to call your service and execute the alerts in then() function. You should also read about promises: http://andyshora.com/promises-angularjs-explained-as-cartoon.html
var objReturn = fileReadFactory.fileRead('myProfile').then(function(){
alert(objReturn.status);
alert(JSON.parse(objReturn.setReadObject));
if(objReturn.status){
var obj= JSON.parse(objReturn.setReadObject);
// alert(obj);
// alert('Inside Object World');
$scope.myprofile = obj;
}
});
Related
can i assign the result from the WL.Client.invokeProcedure(invocationData, options) to a variable.
function getCategory(){
var invocationData = {
adapter : 'Go2needsSQL',
procedure : 'myLatLang',
parameters : []
};
var options = {
onSuccess : procedureSuccess,
onFailure : procedureFailure,
invocationContext: {}
};
var r = WL.Client.invokeProcedure(invocationData, options);
alert(JSON.stringify(r));
}
function procedureSuccess(result){
return result;
}
function procedureFailure(){
alert("Failed");
}
In above code the alert() is giving null json response.
Yes, you can but according to the docs, it returns nothing (undefined)
the result is obtained asynchronously, so when you alert there is no result as the function returns undefined.
You have to use the success handler which is called later when the procedure has been invoked:
function getCategory() {
var result;
var invocationData = {
adapter: 'Go2needsSQL',
procedure: 'myLatLang',
parameters: []
};
var options = {
onSuccess: procedureSuccess,
onFailure: procedureFailure,
invocationContext: {}
};
result = WL.Client.invokeProcedure(invocationData, options);
alert(JSON.stringify(result)); ///this will alert nothing
}
function procedureSuccess(__result) {
result = __result;
alert(JSON.stringify(result)) //this will be okay
}
function procedureFailure() {
alert("Failed");
}
The script is being ran on the android OS at the moment.
Globals File
///Store Global Variables
var Globals = {
Storage: window.localStorage,
OfflineMode: false,
GetSettingsString : function()
{
return JSON.stringify(Settings);
},
SetSettings : function(str)
{
try
{
Settings = JSON.parse(str);
if(Settings.Id != 0)
VelocityMeetings.app.navigate("scan/", { root: true });
}
catch(e)
{
alert(e);
Globals.SetSettings();
}
},
///Experimentation Function
SetSettings: function () {
//Settings = JSON.parse(str);
Settings.OfflineMode = false,
Settings.Username = "mager1794",
Settings.Password = "mn1apwfm",
Settings.Id = 0;
alert("Values Set Manually");
//VelocityMeetings.app.navigate("scan/", { root: true });
},
Init: function () {
// this.SetSettings(/*FileStream.ReadFile("settings.dat")*/);
alert("test2");
this.SetSettings(FileStream.ReadFile("settings.dat"));
alert("test3");
},
Save: function () {
FileStream.WriteFile("settings.dat", GetSettingsString());
}
};
document.addEventListener("deviceready", ondeviceReady(), false);
// Cordova is ready to be used!
//
function ondeviceReady() {
alert("test");
Globals.Init();
}
FileSystem File
var FileStream = {
WriteFile: function (filename, objtoWrite) {
_filename = filename;
_dataobj = objtoWrite;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, _gotFSWrite, fail);
},
WriteFile: function (filename, objtoWrite, type) {
_filename = filename;
_dataobj = objtoWrite;
_type = type;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, _gotFSWrite, fail);
},
ReadFile: function (filename) {
alert("ReadFile Called");
_filename = filename;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, _gotFSRead, fail);
return _dataread;
},
_dataread: null,
_dataobj: null,
_type : "WRITE",
_filename: "",
_gotFileWriter: function (writer) {
writer.onwrite = function (evt) {
_isBusy = false;
};
if(_type=="WRITE")
writer.write(_dataobj);
if (_type == "APPEND")
{
writer.seek(writer.length);
writer.write(_dataobj);
}
writer.abort();
},
_gotFSWrite: function (fileSystem) {
fileSystem.root.getFile(_filename, { create: true }, _gotFileEntryWrite, fail);
},
_gotFileEntryWrite: function (fileEntry) {
fileEntry.createWriter(_gotFileWriter, fail);
},
_gotFSRead: function (fileSystem) {
alert("gotFSRead Called");
fileSystem.root.getFile(_filename, { create: true }, _gotFileEntryRead, fail);
},
_gotFileEntryRead: function (fileEntry) {
alert("gotFileEntryRead Called");
fileEntry.file(_gotFileRead, fail);
},
_gotFileRead: function (file) {
alert("gotFileRead Called");
var reader = new FileReader();
reader.onloadend = function (evt) {
_dataread = evt.target.result;
};
reader.readAsText(file);
},
_fail: function (error) {
throw "File Failed";
}
};
the GotFSRead function is never being reached and I cannot figure out why, I've placed in the alerts just so I can watch as it progressed through the functions. Additionally, can you store a callback in a variable? because it seems that the read file function is going to need a callback in order to successfully receive the data.
Yes, in Javascript functions are objects, so they can be assigned to variables just like you're doing in your code here.
The function references in your FileStream object are missing this references, such as this._gotFSRead. For example:
ReadFile: function (filename) {
alert("ReadFile Called");
this._filename = filename;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, this._gotFSRead, this._fail);
return this._dataread;
},
There are many places where this is missing, and you need to fix your _fail references too.
I try to assign a property of a service object by using the $http but I have confusing results. Why this doesn't work (here is my code):
.service('config', function ($http) {
var config = {
get_host: function () {
if (online == 0) {
return offlineHost;
}
return onlineHost;
},
online: 'false',
host: 'false',
checkConnection: function () {
//this wont work;
/*
$http.get(this.host + http_url ).then(function(response) {
return response.data.ping;
});
*/
//this will work
return 'oke';
},
_load: function () {
this.host = this.get_host();
this.online = this.checkConnection();
this.url_api = this.host + http_url;
if (this.online == 1) {
this.offline_message = 'Maaf aplikasi tidak bisa terkoneksi dengan server atau anda offline';
}
}
};
//run constructor and get value;
config._load();
return config;
}) //end config class
In my controller :
var online = config.online;
alert(online) //return undefined, but the $http request on firebug is showed return value
service:
.service('config', function ($http, $q) {
var config = {
get_host: function () {
if (online == 0) {
return offlineHost;
}
return onlineHost;
},
online: 'false',
host: 'false',
checkConnection: function () {
var deferred = $q.defer();
$http.get(this.host + http_url ).then(function(response) {
$q.resolve(response.data.ping);
});
return $q.promise;
},
_load: function () {
this.host = this.get_host();
this.online = this.checkConnection();
this.url_api = this.host + http_url;
if (this.online == 1) {
this.offline_message = 'Maaf aplikasi tidak bisa terkoneksi dengan server atau anda offline';
}
}
};
//run constructor and get value;
config._load();
return config;
}) //end config class
controller:
config.online.then(function(data){
alert(data);
var online = data;
handleDate(online); // this is a predefined function to handle your data when it's downloaded
});
That's because the $http service calls are asynchronous.
The easiest way to handle this is to make your service return a promise:
return $http.get(this.host + http_url);
(return in front of $http is crucial here). Then anywhere in the code:
config.checkConnection().then(function(response) {
// there you get the response.data.ping
});
See your modified and simplified code here: http://plnkr.co/edit/cCHXCLCG3xJUwAPPlJ3x?p=preview
You can read more about that:
http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls/
http://lennybacon.com/post/2014/03/21/chaining-asynchronous-javascript-calls-with-angular-js
https://docs.angularjs.org/api/ng/service/$q
my code:
var myc = {
utils: {
my_fnc: function(a) {
console.log('This is: '+a);
}
},
run: function(type, name, args) {
if (type == 1) {
//call function in myc.utils
return myc.utils[name].apply(myc.utils, args);
} else {
//call global function
return name.apply(null, args);
}
}
};
function myFnc(a) {
console.log('This is: '+a);
}
example 1:
myc.run(1, my_fnc, new Array('a value'));
it working.
example 2:
myc.run(2, myFnc, new Array('a value'));
it not working, this is error: Uncaught TypeError: undefined is not a function
somebody can help me?
I have a function that sends a request to a server and handles the response in a function. I then want to return the response, but I want it to return it to the parent function (getChannelId) so that for example getChannelId('someUsername') would return "someChannelId":
function getChannelId(username) {
function onSearchResponse(response) {
console.log(response);
var channelId = response.items[0].id;
return channelId; /* This is the value I want to return, but I want to return it within the getChannelId function */
console.log({channelId: channelId });
}
var request = window.gapi.client.youtube.channels.list({
part: 'snippet',
forUsername: username,
});
request.execute(onSearchResponse);
}
How do I get the response back to the parent function?
In getchannelid, you should have a variable that the inside function sets. Instead of just returning the result there...
var tmp;
function onSearchResponse(....) {
....
tmp = channelId;
}
Then you can return tmp in the outer function.
Solved it by continuing the schedule in the onSearchRespone callback.
Full code:
requirejs.config({
baseUrl: '//cdnjs.cloudflare.com/ajax/libs',
paths: {
jquery: "jquery/2.0.3/jquery.min",
jqueryColor: "jquery-color/2.1.2/jquery.color.min",
annyang: "annyang/1.0.0/annyang.min",
prefixfree: "prefixfree/1.0.7/prefixfree.min",
gapi: "https://apis.google.com/js/client.js?onload=onGAPILoaded",
gjsapi: "http://www.google.com/jsapi?noext",
ytpapi: "https://www.youtube.com/iframe_api?noext"
/*,
ytdapi: ""*/
}
});
var player, Ice;
function shuffle(o) {
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
function onGAPILoaded() {
console.log('Google Client API Loaded, Loading YouTube Data API..');
gapi.client.load('youtube', 'v3', onYTPAPILoaded);
}
function onYTPAPILoaded() {
console.log('YouTube Data API Loaded');
gapi.client.setApiKey('AIzaSyBt4dZrv29ut8U0xeYTRFrgH_rB8zil9_M');
}
function onYouTubeIframeAPIReady() {
player = new YT.Player('video-player', {
height: '720',
width: '1280',
suggestedQuality: 'hd720',
events: {
onStateChange: function(e) {
Ice.state = e.data;
console.log({ STATE: Ice.state });
}
}
});
}
requirejs(['jquery', 'jqueryColor', 'annyang', 'prefixfree', 'gapi', 'ytpapi', 'gjsapi'], function() {
Ice = new ice();
if(annyang) {
var commands = {
'Ice search youtube for *exp': function(param) {
Ice.execute('watchSearchList', param);
},
'Ice watch (youtube) channel': function(param) {
Ice.execute('watchChannel', param);
},
'Ice play': function(param) {
Ice.execute('togglePlayback', param);
},
'Ice fit': function(param) {
Ice.execute('fit', param);
},
'test *exp': Ice.test
};
annyang.init(commands);
annyang.start();
}
function ice() {
/*
* Variables of Ice
*/
this.props = {
order: 'viewCount',
part: 'snippet',
type: 'video',
maxResults: 50,
q: '',
channelId: ''
}
this.state = -1;
this.intelligence = 9001;
/*
* Functions of Ice
*/
/* Debug Functions */
this.execute = function(func, param) {
Ice.flash();
Ice.log(func);
Ice[func](param);
};
this.test = function(term) {
Ice.log(term);
};
this.flash = function() {
var oldColor = $('h1').css('color');
$('h1').animate({ 'color': 'black' }, function() {
$(this).animate({ 'color': oldColor });
});
}
this.log = function(log) {
$('h1 span').text(log);
};
/* Video Functions */
this.togglePlayback = function() {
var func = (Ice.state == 1 ? 'pause':'play')+'Video';
console.log(func);
player[func]();
};
this.fit = function() {
var W = $(window).innerWidth(),
H = $(window).innerHeight();
console.log({ W: W, H: H });
player.setSize(W, H);
$('.video-player').addClass('full').css({
'width': W+'px',
'height': H+'px'1
});
};
this.watchChannel = function() {
Ice.props.channelId = Ice.getChannelId(prompt('Write Channel:', 'EthosLab'));
console.log({ channelId: Ice.props.channelId });
Ice.props.order = 'date';
Ice.playVideos();
}
this.watchSearchList = function(q) {
Ice.props.q = q;
Ice.playVideos();
}
this.playVideos = function() {
function onSearchResponse(response) { showResponse(response); }
function showResponse(response) {
console.log(response);
videoList = [];
for(var i = 0; i < response.items.length; i++) {
videoList.push(response.items[0].id.videoId);
}
// videoList = shuffle(videoList);
console.log({ videoList: videoList });
player.loadPlaylist(videoList);
$('.video-player').animate({
'height': '720px',
'width': '1280px',
});
}
console.log(Ice.props);
var request = window.gapi.client.youtube.search.list(Ice.props);
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
};
/* YouTube functions */
this.setChannelIdFromUsername = function(username) {
Ice.props.channelId = Ice.getChannelId(username);
};
this.getChannelId = function(username) {
var channelId = '';
function onSearchResponse(response) {
console.log(response);
Ice.props.channelId = response.items[0].id;
Ice.playVideos();
}
var request = window.gapi.client.youtube.channels.list({
part: 'snippet',
forUsername: username,
});
request.execute(onSearchResponse);
console.log({channelId: channelId });
return channelId;
};
}
this.returnChannelId = function() {
};
});