I created a javascript object that i fill with data, When i return this object to anoother class and run the isError function on the object, i always get true, and i cant figure out why.
This is the new object i've created:
function WSResponse()
{
this.error = new Object();
this.isError = function()
{
if (this.error.status === '0')
{
return false;
}
else
{
return true;
}
}
}
This is my service:
...Some code..
var wsresponse = new WSResponse();
wsresponse.data = responseFromServer.ws_result;
wsresponse.error.status='0';
wsresponse.error.msg = responseFromServer.msg;
return wsresponse;
And this is my controller:
if (response.isError)
{
$scope.isLoginError = true;
}
else
{
$scope.isLoginError = false;
}
From some reason i always get true, when i debug i can see the value is 0 or -1 (string)
What is the problem ?
Thanks
isError is a function, so you need to call it like a function, i.e. response.isError()
if(response.isError) will always return true because you are effectively checking if there is a isError object - in this case function - attached to a response object.
if (response.isError())
{
$scope.isLoginError = true;
}
else
{
$scope.isLoginError = false;
}
Related
I have one problem statement.
Implement a function propertyExists(obj, path) that takes in an object and a path (string) as arguments and returns ‘False’ if the property doesn’t exist on that object or is null, else returns the value of the property.
And here is solution.
function propertyExists(obj,path) {
// Write logic here
let result = obj.hasOwnProperty(path);
if(result)
{
return (obj.path);
}
else
{
return result;
}
}
Is this correct way of doing it?
Multiple issues:
the first name of the function should represent what it is doing,
Path as variable name is vague but propertyName as a variable is clear.
what you should do is either:
write function called, "getValue" it returns value if exist or null
function getValue(obj,propertyName) {
if(!obj) { // if object not exist
return null;
}
return obj[propertyName];
}
write function called, "propertyExists" should return true if exist else false.
function propertyExists(obj,propertyName) {
if(!obj) { // if object not exist
return false;
}
return obj.hasOwnProperty(propertyName);
}
function propertyExists(obj,path) {
// Write logic here
for(i in path){
if(obj.hasOwnProperty(path[i]) === true){
obj = obj[path[i]];
}else{
return false;
}
}
return obj;
}
object->obj,propertyname->path
function propertyExist(obj, path){
if (obj.hasOwnProperty(path)) return obj[path];
else return false;
};
Here, as far as I can understand, the objects could be nested also.
Let's take obj as {"a":{"b":"dadsa"}} and path as ab
Now, the the solution which you have posted will not work. Ideally, it should return dadsa, but it will return false.
Try the below code, it will work for nested objects also.
function propertyExists(obj,path) {
// Write logic here
var val=obj;
for(a of path){
val=val[a];
if(!val)
return false;
}
return val;
}
function propertyExists(obj,path) {
var val = obj;
for (a of path) {
val = val[a];
if (!val){
return false;
}
return val;
}
I have this method:
wordFormDirty = (): boolean => {
var self = this;
angular.forEach(self.word.wordForms, function (wf, key) {
var wordFormNgForm = 'wordFormNgForm_' + wf.wordFormId
if (!self[wordFormNgForm].$pristine) {
return true;
}
});
return false;
};
From what I see this never returns true. Can someone give me advice as to how I can implement this so that a form that's not pristine will make the wordFormDirty() method return true.
can you try this, in this case, if I've undestand the issue, the first time there is a value true the result is set to true otherwise it remains false
wordFormDirty = (): boolean => {
var self = this;
var result = false;
angular.forEach(self.word.wordForms, function (wf, key) {
var wordFormNgForm = 'wordFormNgForm_' + wf.wordFormId
if (!self[wordFormNgForm].$pristine) {
result = true;
}
});
return result;
};
If you wish to get a result directly from walking the Array, consider using other methods than forEach. E.g.:
return Object.values(this.word.wordForms).some(
({ wordFormId }) => !this[`wordFormNgForm_${wordFormId}`].$pristine
);
Ok, this is driving me mad, basically what I am trying to do is create a service to get and evaluate user capabilities, I am using WP REST API. I use restangular to get my JSON data.
At this stage I am testing the function in the controller itself, but no matter where I test it, be it in my custom service using this.method or inside the controller, with or without using $scope the result is always undefined. I know I am missing something either in the way I am returning true or false inside the function, or there is something fundamentally different when it comes to promises in JS. Here is the code:
var current_user = parseInt(o2_i18n.user_id),
currentUserCapabilities,
capability;
$scope.currentUserCan = function(capability) {
if(current_user !== '0') {
wpAPIResource.one('users').get()
.then(function(allUsers){
for (var i = 0; i < allUsers.length; i++) {
if ( allUsers[i].id === current_user ) {
var currentUserCapabilities = allUsers[i].capabilities;
for(var prop in currentUserCapabilities){
if (capability === prop) {
//$log.log( prop );
return prop;
} else {
//$log.log( prop );
return false;
}
}
}
}
}, function(reason){
$log.error(reason);
});
} else {
//The user is not logged in, therefor no capabilities
return false;
}
};
$log.log($scope.currentUserCan('publish_posts'));
if ( $scope.currentUserCan('publish_posts') ) {
$log.log( 'Yes I Can!' );
} else {
$log.warn('No Can\'t Do!');
}
Your currentUserCan function doesn't return anything if current_user !== '0'. You should have it return a promise, for example (for the following you'll need to inject the $q service)
$scope.currentUserCan = function(capability) {
if(current_user !== '0') {
// note the "return" here
return wpAPIResource.one('users').get().then(function(allUsers){
for (var i = 0; i < allUsers.length; i++) {
if ( allUsers[i].id === current_user ) {
var currentUserCapabilities = allUsers[i].capabilities;
for(var prop in currentUserCapabilities){
if (capability === prop) {
return prop;
}
}
}
}
return false;
}, function(reason){
$log.error(reason);
return $q.reject(reason); // you still want the promise to fail
});
} else {
return $q.resolve(false);
// this turns the static value into a promise so the API for this
// function is consistent
}
};
then consume the function like this
$scope.currentUserCan('publish_posts').then(function(can) {
if (can) {
$log.log('Yes I Can!');
} else {
$log.warn("No Can't Do!");
}
});
I also cleaned up your loop a little. In your OP, there was no point in the inner loop and you didn't have a return value if the user was not found in the allUsers array.
Is it possible to avoid declaring global variable and instead assign it the result of the anonymous function?
var logged = false;
Ext.each(userRecords, function (userRecord) {
if (userRecord.get('id') == currentuser) {
if (userRecord.get('password') == currentuserpassword) {
logged = true;
}
}
});
Example:
var logged = Ext.each(userRecords, function (userRecord) {
if (userRecord.get('id') == currentuser) {
if (userRecord.get('password') == currentuserpassword) {
return true;
}
}
});
If you're using Ext JS 4.0 or later, just replace your Ext.each in the second code block with Ext.Array.some and your code will work as is.
Executes the specified function for each array element until the function returns a truthy value. If such an item is found, the function will return true immediately. Otherwise, it will return false.
Using ECMAScript 5 some array method:
var logged = userRecords.some(function (userRecord) {
if (userRecord.get('id') == currentuser) {
if (userRecord.get('password') == currentuserpassword) {
return true;
}
}
return false;
});
For example I have this function with a closure:
function getData() {
var status = 0;
var func = function() {
status++
alert(status);
}
return func;
}
Its works correctly and the variable "status" is visible within the closure function.
But if I transfer the closure code into the separate function the closure variable "status" isn't available:
function getData() {
var status = 0;
var func = function() {
myFunction();
}
return func;
}
function myFunction() {
status++
alert(status);
}
Yes, I can send this variable to the function and then return the changed value. But what if I need recursion in "myFunction"?
function getData() {
var status = 0;
var a = function() {
myFunction(status);
}
return a;
}
function myFunction(status) {
if (status == 0) {
status = 1;
// After calling this function again "status" will reset to 0,
// but I want to save current value (status = 1).
data();
}
return status++;
}
var data = getData();
data();
How can I get one instance of my variable "status" for all calls to the closure function.
Thanks!
Firstly, that doesn't work because JS has lexical scopes, not dynamic scopes. More info on Wikipedia
Secondly, if you want to pass in a variable to a function, and allow that function to mutate it, you need to send something that's an instanceof Object.
0 instanceof Object
false
"" instanceof Object
false
[] instanceof Object
true
({}) instanceof Object
true
(function(){}) instanceof Object
true
You can wrap your number into an object and pass it.
Modified example:
function getData() {
var o = {
status: 0
};
var a = function () {
myFunction(o);
}
return a;
}
function myFunction(o) {
console.log(o);
if (o.status == 0) {
o.status = 1;
// After calling this function again "status" will reset to 0,
// but I want to save current value (status = 1).
data();
}
return o.status++;
}
var data = getData();
data();
Output:
Object {status: 0}
Object {status: 1}
http://jsfiddle.net/Dogbert/Tw7nh/
You could replace this line:
myFunction(status);
with:
status = myFunction(status);
or:
JSFIDDLE: http://jsfiddle.net/KHZRr/
function Data(){
var status = 0;
var a = {
getData : function(){
if( status == 0 ){
status = 1;
return "FIRST, status = " + status;
}else{
return "NOT FIRST, status = " + status;
}
}
}
return a;
}
var data = Data();
alert( data.getData() );
alert( data.getData() );
alert( data.getData() );
Is this what you are looking for?
If I transfer the closure code into the separate function the closure variable "status" isn't available.
True, and that won't change due to JavaScript's scoping rules.
Yes, I can send this variable to the function and then return the changed value. But what if I need recursion in "myFunction"?
Nothing changes. You can use recursion from inside the closure as well.
function getData() {
var status = 0;
function data() {
if (status++ == 0) {
// do anything you want
// including recursive calls to `data()`
}
return status;
}
return data;
}
getData()();