So I am making a rest call to get this JSON Object:
{
"_id":"57a0811276e75ba815d248b0",
"gName":"demo-layout",
"gType":"Content",
"wsId":"57a036c376e75ba815d248ac",
"desc":"Demo-Layout for rapidpage",
"createdDate":"2016-08-02T11:16:34.223Z",
"__v":0
}
Now I want to add an array to this object ,something like this:
{
"_id":"57a0811276e75ba815d248b0",
"gName":"demo-layout",
"gType":"Content",
"wsId":"57a036c376e75ba815d248ac",
"desc":"Demo-Layout for rapidpage",
"createdDate":"2016-08-02T11:16:34.223Z",
"blocks":[], //should be added at runtime
"__v":0
}
So I tried following:
dbPage:any={};
ngOnInit(){
let pageId:string="57a0811276e75ba815d248b0";
this._pagesService.getPageById(pageId).subscribe((Page)=>{
this.dbPage=rapidPage;
console.log(this.dbPage); //this prints the object as shown above
});
this.dbPage.blocks=[];
this.dbPage.blocks.push(block1);
}
But its not modifying the current object,instead its creating new Object as :
{blocks: Array[]}
any inputs?
That's because you're not assigning it in the subscribe call. Due to the async nature of HTTP requests in JavaScript, the code below the subscribe call will be executed before the callback inside the subscribe call.
You can easily fix this by moving the code inside the callback:
dbPage: any = {};
ngOnInit(){
let pageId: string = "57a0811276e75ba815d248b0";
this._pagesService.getPageById(pageId).subscribe((rapidPage) => {
this.dbPage = rapidPage;
console.log(this.dbPage); //this prints the object as shown above
this.dbPage.blocks = [];
this.dbPage.blocks.push(block1);
});
}
Related
I have a JSON array fetched from the service to the controller. I'm able to display the JSON array in the console. But when a specific item from the JSON, is called it display's undefined. So how do I call it correctly so that I can use it in my view.
Controller:
$scope.onViewLoaded = function() {
callingService.getdata($scope.datafetched);
}
$scope.datafetched = function(response) {
debugger;
if (response) {
$rootScope.mainData = response;
$scope.localizeddataTypes = getLocalizedCollection($scope.mainData);
}
}
$scope.editFunction = function(key) {
console.log($scope.mainData);
debugger;
console.log($scope.mainData.keyValue);
}
Here console.log($scope.mainData); display's the JSON array but console.log($scope.mainData.keyValue); is displayed as undefined. And my JSON looks like
{
keyValue: "1234DEF56",
animals: {
name:"dog",
color:"brown"
},
birds:{
name:"canary",
color:"yellow"
}
}
So, how do I overcome this problem and why do I get it as Undefined.
Just a curiosity stuff. I feel that the content in that variable is stored in string format and not JSON or JavaScript Object. Try this, and see if that works?
$scope.mainData = JSON.parse($scope.mainData);
console.log($scope.mainData.keyValue);
I'm new to Angular2 and somehow it's really hard to me to understand how http works in Angular2. I made a simple component which should display a json response. It doesn't work and I have no idea why. I checked many tutorials and tried it with promises as well as observables. Doesn't work. I just can't get the data of the response.
My code:
private doAction() {
this.doHttpRequest().subscribe(
data => this.content = data
);
this.content = JSON.stringify(this.content);
}
private doHttpRequest() {
return this.http.get('http://jsonplaceholder.typicode.com/posts/1')
.catch(this.handleError);
}
this.content is bind to my template. When I click a button to start doAction() for a second I see "" in the template, after another second [object Object]
What is the problem here?
That's the expected behavior
private doAction() {
// schedule HTTP call to server and subscribe to get notified when data arrives
this.doHttpRequest().subscribe(
// gets called by the observable when the response from the server aarives
data => this.content = data
);
// execute immediately before the call to the server was even sent
this.content = JSON.stringify(this.content);
}
To fix it change it to
private doAction() {
this.doHttpRequest().subscribe(
data => {
//this.content = data;
this.content = data.json());
});
);
}
If you want code to be executed after data arrived, then you need to move it inside the subscribe(...) callback.
Since http requests are asynchron you have to put all your logic depending on the results of the http call in the subscribe() callback like this:
private doAction() {
this.doHttpRequest().subscribe(
data => {
this.content = data;
// any more logic must sit in here
}
);
}
private doHttpRequest() {
return this.http.get('http://jsonplaceholder.typicode.com/posts/1')
.map(res => res.json());
.catch(this.handleError);
}
Http call is returning data since it shows "[object Object]" in template. If you want to see the json data in template you can use the json pipe as below.
{{content | json}}
PS: No need of "this.content = JSON.stringify(this.content);" in your code.
I have a JSON file, which contains:
{
"/default.aspx": "headerBg",
"/about.aspx": "aboutBg",
"/contact.aspx": "contactBg",
"/registration.aspx": "regBg",
"/clients.aspx": "clientsBg",
"/onlinesessions.aspx": "bg-white-box",
"/ondemamdsessions.aspx": "bg-grey"
}
Now I am reading this json file using $http, but I want to add a filter in below fashion:
Using window.location.pathname, I am reading path of the current page, suppose the current page is /about.aspx
Then I want to add a filter in $http response by which I want to read only aboutBg.
The code I wrote can retrieve all the values, but unable to filter that. Please help.
User this function where you receive the response.
function getPageBgClass(currentPage, responseData) {
if (responseData.hasOwnProperty(currentPage))
return responseData[currentPage]
else
return "none"
}
Here is how it should be used in your promise then function
function(response) {
var bg = getPageBgClass(window.location.pathname, response.data);
//Your code here ...
}
there is no direct method to get key using value from json.
you should make sure that there are no 2 keys having same value for below code to work
function swapJsonKeyValues(input) {
var one, output = {};
for (one in input) {
if (input.hasOwnProperty(one)) {
output[input[one]] = one;
}
}
return output;
}
var originaJSON = {
"/default.aspx": "headerBg",
"/about.aspx": "aboutBg",
"/contact.aspx": "contactBg",
"/registration.aspx": "regBg",
"/clients.aspx": "clientsBg",
"/onlinesessions.aspx": "bg-white-box",
"/ondemamdsessions.aspx": "bg-grey"
}
var invertedJSON = swapJsonKeyValues(originaJSON);
var samplepathname = "aboutBg";
var page = invertedJSON[samplepathname];
[function swapJsonKeyValues from https://stackoverflow.com/a/1970193/1006780 ]
First time using Angular JS, I'm using $http.get to return a Json object. When I output the response data, I can see entire JSON object in the console, but I can't access the object or properties. What am I missing here?
$scope.init = function (value) {
$scope.productEditorModel.productId = value;
$scope.loadData($scope.productEditorModel.productId);
}
$scope.loadData = function (productId) {
var responsePromise = $http.get("/Product/GetProductModel", {
params: { productId: productId }
});
responsePromise.success(function (dataFromServer, status, headers, config) {
console.log(dataFromServer.DataModel);
});
};
When I first output the dataFromServer to the console, the object is null and then it becomes populated. Since it's an async call, I should be able to access and set whatever vars inside the success
I would like to be able to directly access the object and property names IE:
$scope.productModel.productId = dataFromServer.Data.productId
My json looks like this:
Object{DataModel:Object, IsSuccess: false}
Thanks!
The problem is that you are trying to access the data before it comes back. Here is a plunker that demonstrates how to set it up, and how not to.
//predefine our object that we want to stick our data into
$scope.myDataObject = {
productId: 'nothing yet',
name: 'nothing yet'
}
//get the data, and when we have it, assign it to our object, then the DOM will automatically update
$http.get('test.json')
.success(function(data) {
$scope.myDataObject = data
});
var y = $http.get('test.json')
//this throws an error because I am trying to access the productId property of the promise object, which doesn't exist.
console.log(y.productId);
Here is the demo
My Controller Method:
[HttpGet]
Public ContentResult GetData()
{
var jsonstring = "{{col: \"aaaaa\"},{col:\"bbbbbb\"},{col: \"cccccc\"}}";
return Content(jsonstring,"application/json");
}
My Ajax Call:
$.get("GetData", function (data) {
alert("back");
$.each(data, function (index, item) {
alert(item);
//loop thru item and add to drop downs, make drop downs visible
});
});
The Controller method is getting called properly and does return, however It does not return back to the ajax call. I would like to use JsonResult and return Json(....) however, I have a process that pre builds the Json string for me. Do I need to deserialize it first? Thank you all.
You have a poorly formed Json string - change outer brackets to [ ], and put double quotes around each key ie. "col":
This change will allow the content to be processed by the ajax call.