Angular Service returns String as dictionary - angularjs

I have a service as
angular.module('inviteService', ['ngResource']).factory('Invite', function ($resource) {
return $resource('/invite');
});
and my controller is
$scope.invite = function () {
console.log("submitting invite for " + $scope.email);
var invite = new Invite();
Invite.save({'email': $scope.email}, function (data) {
console.log('data is: ' + data);
$scope.message.type = 'info';
$scope.message.content = data;
// console.log('controller message' + JSON.stringify($scope.message, null, 2));
// reset email input box
$scope.email = undefined;
});
and relevant directive code as
scope.$watch('ngModel', function () {
if (Object.keys(scope.ngModel).length > 0) {
console.log('directive message: ' + JSON.stringify(scope.ngModel));
element.show();
//noinspection JSUnresolvedFunction
$timeout(function () {
//element.empty();
element.fadeOut("slow");
}, 1000);
}
}, true);
When I run the code, I see in Chrome Network tab the response as
"You are already on our invite list"
But the Angular code console shows me
data is: [object Object] notificationController.js:13
directive message:{
"type": "info",
"content": {
"0": "\"",
"1": "Y",
"2": "o",
"3": "u",
"4": " ",
"5": "a",
"6": "r",
"7": "e",
"8": " ",
"9": "a",
"10": "l",
"11": "r",
"12": "e",
"13": "a",
"14": "d",
"15": "y",
"16": " ",
"17": "o",
"18": "n",
"19": " ",
"20": "o",
"21": "u",
"22": "r",
"23": " ",
"24": "i",
"25": "n",
"26": "v",
"27": "i",
"28": "t",
"29": "e",
"30": " ",
"31": "l",
"32": "i",
"33": "s",
"34": "t",
"35": "\""
}
}
Why is that data is not coming as string?

ngResource expects an object or an array of objects in the response from the server.
See https://stackoverflow.com/a/13816008/215945 for your options:
use $http instead of $resource
return an object from your server (probably the easiest approach, if you can modify the server): { "str": "'You are...'"}
intercept and modify the returned value (probably too much work)

Related

React State cannot update array with intervals correctly

I'm trying to make a simple animation with JS: I want to randomise a series of letters of a title for an interval of time and after a timeout set the title to the company title basically.
Here's the code I've written so far:
const alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
"O", "P", "Q", "R", "S", "T", "I", "U", "V", "W", "X", "Y", "Z", "~", "&", "|", "^", "ç", "#", "]",
"[", "{", "}", "ù", "*", "µ", "¤", "$", "£", "€", "°", ")", "(", "+", "-", "/", "<", ">", "²", "`", "é",
"è", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"];
const randomFromAlphabet = () => alphabet[(Math.floor(Math.random() * alphabet.length))];
const companyTitle = ['C', 'U', 'I', 'R', 'C', 'K'];
const AboutUs = () => {
const [title, setTitle] = useState(Array.from({ length: companyTitle.length }, () => randomFromAlphabet()));
const [intervals, setIntervals] = useState([]);
const letterRandomize = () => {
const generatedIntervals = Array.from({ length: title.length }, (_, index) => {
return setInterval(() => {
const arrayTitle = Array.from(title);
arrayTitle[index] = randomFromAlphabet();
setTitle(arrayTitle);
}, 350 * (index + 1));
});
setIntervals(generatedIntervals);
};
useEffect(() => {
letterRandomize();
setTimeout(() => {
for (var i = 0; i < companyTitle.length; i++) {
clearInterval(intervals[i]);
const newTitle = [...title];
newTitle[i] = companyTitle[i];
setTitle(newTitle);
}
}, 3000)
}, []);
I know it's not very good written, it's because I'm trying to understand what the problem is.
I've encountered two problems: the first one is the update of the randomised letters:
I've noticed that everytime I update one letter of the array the other go back to the originals.
So for example if we have 'CUIRCK' and after one update we have 'CAIRCK' after another update the second letter returns to 'U', like 'CUIRCB'.
The second problem is that I cannot clear the intervals. I've created 6 different intervals and put them in my state, I don't what I'm doing wrong.
just created a Sandbox which should solve your problem. State inside Intervals can be tricky and you should avoid it. SetState is running async, since setInterval also runs your function async inside an interval you are referring to a state which could not have been already updated to the value you want. I hope I explained myself well enough.
https://codesandbox.io/s/randomized-title-oozo6

How to get multiple elements from an Array?

I'm using discord.js and I want to create a "server" with passcode. I want the passcode to be 6 letters long, so far I can only do one.
It has to be random as well. Like "ZSHWJK" Instead of "AAAAAA"
Code:
var serverPasscode = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
module.exports = {
name: "createserver",
description: "Creates a server",
run(message, args, client){
const newServer = new MessageEmbed()
.setTitle(`${message.author.name}'s server`)
.setFooter(`${serverPasscode[Math.floor(Math.random() * serverPasscode.length)]}`)
message.channel.send(newServer);
}
};
Right now this can only return one element which is not what I want.
You could use a for loop and create a function such as this:
function makeGuildPassword(length) {
var result = ''; // create empty string that you will add random characters to
var characters = // list of characters (you can change this however you want)
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i = 0; i < length; i++) { // create a loop
// add a random character to the string; restart the loop
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
};
console.log(makeGuildPassword(6))

filter String with empty String in if statement, iOS

I'm working on a custom keyboard. I'm having trouble filtering Strings Array. I want to filter the array only in if statement, I have an array with letters and empty String's. I want to filter Array only in if statement because I want to remove last character, not empty String.
Here is my code:
keyboardKeyStr = ["h", "e", "l", "l", "o", " ", "", "t", "h", "i", "s", "", "i", "s", " ", "m", "y", " ", "", "a", "r", "r", "a", "y", " "]
if range.length == 1 && text.count == 0 {
print("Delete Button")
let emptyStr: String? = ""
keyboardKeyStr = keyboardKeyStr.filter {$0 != emptyStr}
keyboardKeyStr.removeLast()
keyboardKeyArr.append(keyboardView.deleteBtn)
self.keyboardKeyStr.append("")
}
Try this keyboardKeyStr = keyboardKeyStr.filter{ $0 != "" && $0 != " "}

How to generate random string form array of elements by compared with another array of elements in swift?

I aware to get random character from a string. From here is the code,
func randomString(_ length: Int) -> String {
let master = Array("abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ_123456789".characters) //0...62 = 63
var randomString = ""
for _ in 1...length{
let random = arc4random_uniform(UInt32(master.count))
randomString.append(String(master[Int(random)]))
}
return randomString
}
Usage :
var randomArray1 = [String]()
for _ in 0...62{
randomArray1.append(self.randomString(1))
}
Here, If randomArray1.append(self.randomString(x)), then x = 1...N
Checking repeated elements :
var sameElementCatcher = [String]()
for x in 0...62{
let element = randomArray1[x]
randomArray1[x] = ""
if randomArray1.contains(element){
sameElementCatcher.append(element)
}
}
print("Same Elements")
print(sameElementCatcher.count != 0 ? sameElementCatcher : "Array count is zero")
Output:
Same Elements
["_", "u", "8", "7", "E", "P", "u", "y", "C", "-", "C", "x", "l", "j",
"t", "D", "U", "2", "e", "2"]
But I need to get array of 62 unique random characters from master by compared with randomArray1. i.e., Array count is zero
How can I achieve this without delay?
Note:
Also, I read this post also I have a answer for shuffling array. But this post different from shuffling only, Please, see usage.
Did you try like this?
What I understand from your question. generate a random text where all the characters are unique.
Before appending your random string to your array check is array have that char then append into your array.
func randomString(_ length: Int) -> String {
let master = Array("abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ_123456789".characters) //0...62 = 63
var randomString = ""
for _ in 1...length{
let random = arc4random_uniform(UInt32(master.count))
randomString.append(String(master[Int(random)]))
}
return randomString
}
var randomArray1 = [String]()
var tempRandomString = ""
let totalRandomCount = 62
var randomArrayCount = 0
while (totalRandomCount > randomArrayCount) {
tempRandomString = randomString(1)
if !randomArray1.contains(tempRandomString) {
randomArray1.append(tempRandomString)
randomArrayCount+=1
}
}
print(randomArray1)
Output: ["X", "u", "j", "1", "n", "E", "D", "q", "U", "6", "T", "O", "f", "J", "i", "c", "W", "V", "G", "R", "k", "7", "_", "8", "-", "l", "w", "4", "e", "Q", "C", "m", "M", "Y", "o", "S", "B", "2", "Z", "P", "p", "N", "y", "H", "a", "h", "z", "s", "b", "A", "3", "g", "x", "L", "v", "F", "d", "r", "t", "K", "9", "5"]
I tried this with playground. For this output 199 times loop executed.
If anyone knows better than this update yours.

JSON array iteration skips first element - NodeJS

Ive got this JSON markup:
"Categories": [
{"name": "a", "id": "1"},
{"name": "b", "id": "2"},
{"name": "c", "id": "3"},
{"name":"d", "id": "4"},
{"name":"e", "id": "5"},
{"name": "f", "id": "6"},
{"name": "g", "id": "7"},
{"name": "h", "id": "8"}
]
Ive got a setInterval going over each of these categories and making a new Promise for each one.
For some unknown reason, it always skips the first element and exists with an out of bounds exception
var i = 0;
var id = setInterval(function(){
if (i == categories.length){
clearInterval(id);
}
client.itemSearch({
category: categories[i].id,
catName: categories.name,
}).then(function(results){
console.log("From category - " + categories[i].name + "\n" +
"Title: " + results[0].Title);
},function(err) {
console.log("error at " + categories[i].name);
});
i+=1;
}, 1000);
The problem is that you're referencing i in your promise callbacks and i changes every second. So your callbacks are being executed sometime in the future when i === categories.length, which would be an invalid index.
Since you already have a closure, just store the current category object in a variable outside of your promise callbacks and reference that instead.
You're also letting the function continue when i === categories.length which will cause an invalid index access.
Here's an example of a solution that fixes the aforementioned issues:
var i = 0;
var id = setInterval(function() {
if (i === categories.length) {
clearInterval(id);
return;
}
var category = categories[i];
client.itemSearch({
category: category.id,
catName: category.name,
}).then(function(results) {
console.log("From category - " + category.name + "\n" +
"Title: " + results[0].Title);
}, function(err) {
console.log("error at " + category.name);
});
i += 1;
}, 1000);
Lastly, you originally had catName: categories.name but I changed it to catName: category.name as I assumed that may have been your original intention.

Resources