Interpolate string with dynamic data with angular2 - javascript

I'm loading up data from the server via ajax requests. The JSON file has configurations for popups in the site.
popupData: {
data:{ var_one: "hello", var_two: "world"},
template: "the <b>{{var_two}}</b> say's {{var_one}}"
}
The variable names and template will be different for every occurrence of the popup.
How can I get this string interpolated with the data that comes with it? I need to pass the pre-built string to a component to be viewed using [innerHTML].

Somewhere after the data was received:
const popupString = popupData.template.replace(
/{{\s?([^{}\s]*)\s?}}/g,
(substring, parsedKey) => {
const replacer = popupData.data[parsedKey];
return typeof replacer !== 'undefined' ? replacer : substring;
}
);
It should equal the <b>world</b> says Hello in your example.
Please note that this code comes from robisim74’s angular-l10n (MIT license).

Related

passing non-url encoded parameters to an ajax call in node.js

I am trying to pass parameters from my website to a couchdb server through a node.js server.
I absolutely need to pass {} in a url. Not a string, not an empty object, the actual {} characters. It is used to define the end_key parameter in couchdb views.
At the moment, my call goes like this :
let url = "/trades";
let ajax_options = {
data:{
design_name:'bla',
view_name:'blabla',
params_view:{
group_level:2,
start_key:["1",0],
end_key:["1",{}]
}
}
};
$.ajax(url,ajax_options).then((res) => { ... });
when it passes through NodeJs and the nano library with
db.view(req.query.design_name, req.query.view_name, req.query.params_view)
the end_key object in params_view becomes ["1"] instead of ["1",{}] which I would like to see.
I have verified that with the correct value for end_key, the view gives me the expected result.
How to prevent that behavior from occurring ?

Mapping a JSON response to component model in TypeScript.

I have an Angular 2 app that returns a JSON string. I want to take that JSON string and map its values to a model.
From my understanding, a TypeScript model file is supposed to help in mapping an HTTP Get response to an object - in my case a class classed 'CustomObject'.
Here's my TypeScript model file which I created for TypeScript to recognize:
export class CustomObject {
public Name: string;
}
Here's what my JSON string looks like (slightly modified from Chrome dev tools to eliminate unnecessary variables):
"{
"EventType": 3,
"Description": "Test Description",
"LocationName": "DefaultLocation",
"Name": "TestName"
}"
I want to take that JSON string and map the 'Name' value ("TestName" to an existing CustomObject's variable I have declared in my home.ts file which is null by default:
public activeCustomObject: CustomObject = null;
However, after executing the HTTP Get method to retrieve the JSON response (I expect variable 'activeCustomObject' to now its 'Name' field set to 'TestName', calling {{activeCustomObject.Name}} in my HTML file print nothing. I've done the proper imports and set the providers.
Here's how I'm subscribing:
this._customObjectService.getCustomObject()
.subscribe(res => {
this.activeCustomObject = res;
});
and this is how I'm calling the GET method:
getActiveCustomObject() {
return this._http.get('/test/customobject')
.map((response) => {
console.log(response);
return response.json;
});
}
Any ideas as to why calling {{activeCustomObject.Name}} print nothing in my HTML? Chrome dev tools show the JSON is returning a proper JSON string with the data I need (mainly name). I plan to use the other values in the JSON string so I can't just make the HTTP GET return the name field - I need to know why the returned JSON string isn't getting mapped to the Custom Object variable.
I think that it's because your data are loaded asynchronously. I guess that you have an error in your JavaScript console...
You could try to use the Elvis operator this way:
{{activeCustomObject?.Name}}
I see also another problem. You need to call the json method on the response not a property:
getActiveCustomObject() {
return this._http.get('/test/customobject')
.map((response) => {
console.log(response);
return response.json(); // <-----------
});
}

how to deal with JSON response

I'm using Python websockets to return JSON objects (I think) however I'm not sure how to deal with the response. I have an example using JavaScript which uses parseJSON, a snippet is bellow:
socket = io.connect("__socket address__");
socket.on("connect", function() {socket.emit("subscribe_areas", areas)});
var d = jQuery.parseJSON(c);
console.log(d);
d.type == "INTERPOSE";
which returns data I can access eg d.type == "INTERPOSE";:
Object {area: "BE", type: "MOVE", to: "0109", from: "0107", value: "2L65"}
Object {area: "BE", type: "MOVE", to: "0113", from: "0109", value: "2L65"}
where as my Python I recieve:
(u'{"area":"EH","type":"INTERPOSE","to":"B243","value":""}',)
(u'{"area":"EH","type":"INTERPOSE","to":"0337","value":""}',)
(u'{"area":"EH","type":"INTERPOSE","to":"0085","value":""}',)
Why does the python return JSON wrapped in brackets and commars? My Python is bellow:
from socketIO_client import SocketIO
import logging
import json
def on_connect():
print('CONNECTED')
areas = ['EH']
socketIO.emit('subscribe_areas', areas)
def on_message(*answer):
print(answer)
socketIO = SocketIO('_address_', _port_)
socketIO.on('connect', on_connect)
socketIO.on('message', on_message)
socketIO.wait()
I've tried decoding using json.load, json.loads, json.decode but recieve all sorts of errors. What am I missing and why is the return wrapped in brackets and such?
You told Python to expect 0 or more arguments:
def on_message(*answer):
print(answer)
Python then gives you a tuple of all arguments passed in; your print statements show you got one argument, so you got a tuple with just one element in it. That one element is a JSON string that you'd decode with json.loads().
Take the first element and decode that:
def on_message(*answer):
print(json.loads(answer[0]))
or don't use * and require that one argument is passed in, always and load from that one argument
def on_message(answer):
print(json.loads(answer))

Url hash fragment format

I need to save the UI state in the hash fragment, I tried two different methods:
1- hash fragment with a query string format
#a=foo&b=bar
and then get a value with a custom function:
getParam: function (parameter) {
if(document.location.hash !== "") {
var param = document.location.hash.substring(1).split("&");
for(var i in param) {
var keyValue = param[i].split('=');
if(keyValue.length === 2 && keyValue[0] === parameter) {
return $.trim(keyValue[1]);
}
}
}
return null;
}
2- hash fragment with a json object
#{"a":"foo","b":"bar"}
and then get the object with
$.parseJSON(document.location.hash.substring(1))
What is the best methods? Is there a specific convention for the hash fragment format?
Best practise is to leave the fragment id alone. Use the history api to change a real query string.
Then, when the page is requested from scratch, build it entirely on the server.
This:
Avoids the need to load a base page before immediately replacing large chunks of it with Ajax data (which used to make the Twitter web app horrible to use until they moved to the history api)
Makes links friendly for search engines and other non-JS clients

How can javascript parse a Rails generated query string with nested values into JSON?

Rails allows the generation of query strings by passing a hash to a url_for type helper:
root_path({ :animals => {:dogs => ['pluto','spot'], :cats => 'garfield'} })
This will generate a url like:
http://example.com/?animals[dogs][]=pluto&animals[dogs][]=spot&animals[cats]=garfield
I want to use javascript to turn this into a JSON object so I have an object that matches the hash passed into the url helper in rails.
Using prototype.js I can call:
var params = window.location.search.toQueryParams();
params is a object but the original nested structure is not retained, instead I get:
{
"animals[dogs][]" : ["pluto","spot"],
"animals[cats]" : "garfield"
}
What I really want is:
{
"animals" : {
"dogs" : ["pluto","spot"],
"cats" : "garfield"
}
}
Also the reverse would be useful too. Prototype.js has toQueryString which in this case just returns an empty string:
Object.toQueryString({
"animals" : {
"dogs" : ["pluto","spot"],
"cats" : "garfield"
}
});
Is there a library of method that provides for this?
To answer my own question:
I found Ben Alman's jQuery BBQ which does it with a jQuery plugin.
http://benalman.com/code/projects/jquery-bbq/examples/deparam/?animals[dogs][]=pluto&animals[dogs][]=spot&animals[cats]=garfield

Categories

Resources