The following tutorial points to an external json file. But it is blocked by CORS policy. How can I declare the object locally in order to populate the web table?
Codepen: https://codepen.io/centem/pen/Rwbmmdy
Thank you.
var app = angular.module('myApp', []);
app.controller('myController',
function ($scope, $http) {
var request = {
method: 'get',
url: 'https://www.encodedna.com/angularjs/tutorial/birds.json',
dataType: 'json',
contentType: "application/json"
};
$scope.arrBirds = new Array;
$http(request)
.success(function (jsonData) {
$scope.arrBirds = jsonData;
$scope.list = $scope.arrBirds;
})
.error(function () {
});
});
Simply declare the variable you want with the json data:
$scope.list = [
{
"ID": "001",
"Name": "Eurasian Collared-Dove",
"Type": "Dove"
},
{
"ID": "002",
"Name": "Bald Eagle",
"Type": "Hawk"
},
{
"ID": "003",
"Name": "Cooper's Hawk",
"Type": "Hawk"
},
{
"ID": "004",
"Name": "Bell's Sparrow",
"Type": "Sparrow"
},
{
"ID": "005",
"Name": "Mourning Dove",
"Type": "Dove"
},
{
"ID": "006",
"Name": "Rock Pigeon",
"Type": "Dove"
},
{
"ID": "007",
"Name": "Abert's Towhee",
"Type": "Sparrow"
},
{
"ID": "008",
"Name": "Brewer's Sparrow",
"Type": "Sparrow"
},
{
"ID": "009",
"Name": "Canyon Towhee",
"Type": "Sparrow"
},
{
"ID": "010",
"Name": "Black Vulture",
"Type": "Hawk"
}];
Related
I am integrating an API in react native, where I am facing a parsing error. But, from the postman, it works fine.
I have tried to send an image through uri, blob, base64 string but facing the same issue.
Below is my react-native code:
var data = new FormData();
data.append("ImgInput", "/IMG_20161229_140335993.jpg");
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "http://212.48.69.65:7465/Core.svc/UploadImage?ApplicationName=www_spoiltpigrewards_com&SessionToken=7E2BE649-3136-4074-9B88-670D717C5828&UserName=jatin1#gmail.com&StoreName=Cooperative&NumberOfProducts=2&Multishot=true&MultishotGuid=00000000-0000-0000-0000-000000000000&FileNumber=1&MaxFileNumber=2");
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(data);
below is postman collection in json format. it works fine. I want same output from react-native code.
{
"info": {
"_postman_id": "7a0149d0-c96c-4431-8978-1b619968edf7",
"name": "SpoiltPig",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "http://212.48.69.65:7465/Core.svc/UploadImage?ApplicationName=www_spoiltpigrewards_com&SessionToken=7E2BE649-3136-4074-9B88-670D717C5828&UserName=jatin1#gmail.com&StoreName=Cooperative&NumberOfProducts=2&Multishot=true&MultishotGuid=00000000-0000-0000-0000-000000000000&FileNumber=1&MaxFileNumber=2",
"request": {
"method": "POST",
"header": [
],
"body": {
"mode": "formdata",
"formdata": [
{
"key": "ImgInput",
"value": null,
"type": "file"
}
]
},
"url": {
"raw": "http://212.48.69.65:7465/Core.svc/UploadImage?ApplicationName=www_spoiltpigrewards_com&SessionToken=7E2BE649-3136-4074-9B88-670D717C5828&UserName=jatin1#gmail.com&StoreName=Cooperative&NumberOfProducts=2&Multishot=true&MultishotGuid=00000000-0000-0000-0000-000000000000&FileNumber=1&MaxFileNumber=2",
"protocol": "http",
"host": [
"212",
"48",
"69",
"65"
],
"port": "7465",
"path": [
"Core.svc",
"UploadImage"
],
"query": [
{
"key": "ApplicationName",
"value": "www_spoiltpigrewards_com"
},
{
"key": "SessionToken",
"value": "7E2BE649-3136-4074-9B88-670D717C5828"
},
{
"key": "UserName",
"value": "jatin1#gmail.com"
},
{
"key": "StoreName",
"value": "Cooperative"
},
{
"key": "NumberOfProducts",
"value": "2"
},
{
"key": "Multishot",
"value": "true"
},
{
"key": "MultishotGuid",
"value": "00000000-0000-0000-0000-000000000000"
},
{
"key": "FileNumber",
"value": "1"
},
{
"key": "MaxFileNumber",
"value": "2"
}
]
}
},
"response": []
}
]
}
This question already has answers here:
not able to access $scope object outside a http response callback function in angularjs
(3 answers)
Closed 5 years ago.
I'm trying to get a json file within a a controller with $http.get. All well until I try to access the property which holds the response. If I try console.log(property) inside the $http.get() it outputs the returned object, outside $http.get() accessing the very same property and it outputs undefined!
I even try to attache it to the $scope and it's the same result?!
angular.module('todayfmApp')
.controller('MainCtrl', ['$http', '$scope', function ($http, $scope) {
var self = this;
$http.get('data/form-data.json').then(function(response) {
self.formdata = response.data;
console.log(self.formdata);
});
console.log(self.formdata);
}]);
{
"settings": {
"version": "",
"Step": "",
"filterBreak": "",
"pid": ""
},
"category": [
{ "name": "Select All", "selected": true },
{ "name": "Carlow", "value": "Carlow" },
{ "name": "Cavan", "value": "Cavan" },
{ "name": "Clare", "value": "Clare" },
{ "name": "Cork", "value": "Cork" },
{ "name": "Derry", "value": "Derry" },
{ "name": "Donegal", "value": "Donegal" },
{ "name": "Down", "value": "Down" },
{ "name": "Dublin", "value": "Dublin" },
{ "name": "Galway", "value": "Galway" },
{ "name": "Kerry", "value": "Kerry" },
{ "name": "Kildare", "value": "Kildare" },
{ "name": "Kilkenny", "value": "Kilkenny" },
{ "name": "Laois", "value": "Laois" },
{ "name": "Leitrim", "value": "Leitrim" },
{ "name": "Limerick", "value": "Limerick" },
{ "name": "Louth", "value": "Louth" },
{ "name": "Mayo", "value": "Mayo" },
{ "name": "Meath", "value": "Meath" },
{ "name": "Monaghan", "value": "Monaghan" },
{ "name": "Offaly", "value": "Offaly" },
{ "name": "Roscommon", "value": "Roscommon" },
{ "name": "Sligo", "value": "Sligo" },
{ "name": "Tipperary", "value": "Tipperary" },
{ "name": "Waterford", "value": "Waterford" },
{ "name": "Westmeath", "value": "Westmeath" },
{ "name": "Wexford", "value": "Wexford" },
{ "name": "Wicklow", "value": "Wicklow" }
],
"num_nights": [
{ "name": "1 Night", "value": 1, "selected": true},
{ "name": "2 Nights", "value": 2 },
{ "name": "3 Nights", "value": 3 },
{ "name": "4 Nights", "value": 4 },
{ "name": "5 Nights", "value": 5 },
{ "name": "6 Nights", "value": 6 },
{ "name": "7 Nights", "value": 7 }
],
"num_rooms": [
{ "name": "1 Room", "value": 1, "selected": true },
{ "name": "2 Rooms", "value": 2 },
{ "name": "3 Rooms", "value": 3 },
{ "name": "4 Rooms", "value": 4 }
],
"num_adults": [
{ "name": "1 Adult", "value": 1 },
{ "name": "2 Adult", "value": 2, "selected": true }
],
"num_child": [
{ "name": "0 Kids", "value": 0, "selected": true },
{ "name": "1 Kids", "value": 1 },
{ "name": "2 Kids", "value": 2 }
]
}
In your case the problem is that $http.get response data is a late binding method. The response of this method will be available only after the service call is finished. This is an asynchronous method so that this will not be accessible inside scope as you expect. For that you need to bind your response inside a $scope variable and use it later inside a function call.
You will need to call the self.getResponseData method at first, say at the time of controller initialization. There after call a method self.logResponseData to log the response data.
You may need to change your calls something like this.
angular.module('todayfmApp')
.controller('MainCtrl', ['$http', '$scope', function ($http, $scope) {
var self = this;
// Get the response data with service call
self.getResponseData = function(){
$http.get('data/form-data.json').then(function(response) {
self.formdata = response.data;
console.log(self.formdata);
});
}
//Method to read the response data later
self.logResponseData = function() {
console.log(self.formdata);
}
//Call the method at the time controller loaded to initialize the `self` variable
self.getResponseData();
}]);
self.formdata = response.data.jsondatavariablename;
// Use the JSON data name
$http.get() is asynchronous which roughly means that when you call this it sends request and doesn't stop code on here to wait until it responded, next statements execution is continued though response is still hasn't come and you have no data from it. That's why you need callback function in .then() method, it is being called when you get your response, where you can use your response data. For example, you can assign it to some $scope property and it will update this value everywhere you use this property.
$http uses so called Promises to achieve this. I tried to make it simple but if you want know more detailed how it works, guess that's what will help you: Promise
According to https://developers.google.com/gmail/api/v1/reference/users/messages/get
it seems choosing either 'full' and 'raw' formats are the options to obtain an email's body.
Is there a way to fetch email body, but not attachments?
The format raw will give you everything in the mail (attachments included). The format full will however give you ids for attachments instead of the data, so full is the format you want to use.
Here is an example of how to get the body from a full format response:
var response = {
"payload": {
"parts": [
{
"mimeType": "multipart/alternative",
"filename": "",
"headers": [
{
"name": "Content-Type",
"value": "multipart/alternative; boundary=001a1142e23c551e8e05200b4be0"
}
],
"body": {
"size": 0
},
"parts": [
{
"partId": "0.0",
"mimeType": "text/plain",
"filename": "",
"headers": [
{
"name": "Content-Type",
"value": "text/plain; charset=UTF-8"
}
],
"body": {
"size": 9,
"data": "V293IG1hbg0K"
}
},
{
"partId": "0.1",
"mimeType": "text/html",
"filename": "",
"headers": [
{
"name": "Content-Type",
"value": "text/html; charset=UTF-8"
}
],
"body": {
"size": 30,
"data": "PGRpdiBkaXI9Imx0ciI-V293IG1hbjwvZGl2Pg0K"
}
}
]
},
{
"partId": "1",
"mimeType": "image/jpeg",
"filename": "feelthebern.jpg",
"headers": [
{
"name": "Content-Type",
"value": "image/jpeg; name=\"feelthebern.jpg\""
},
{
"name": "Content-Disposition",
"value": "attachment; filename=\"feelthebern.jpg\""
},
{
"name": "Content-Transfer-Encoding",
"value": "base64"
},
{
"name": "X-Attachment-Id",
"value": "f_ieq3ev0i0"
}
],
"body": {
"attachmentId": "ANGjdJ_2xG3WOiLh6MbUdYy4vo2VhV2kOso5AyuJW3333rbmk8BIE1GJHIOXkNIVGiphP3fGe7iuIl_MGzXBGNGvNslwlz8hOkvJZg2DaasVZsdVFT_5JGvJOLefgaSL4hqKJgtzOZG9K1XSMrRQAtz2V0NX7puPdXDU4gvalSuMRGwBhr_oDSfx2xljHEbGG6I4VLeLZfrzGGKW7BF-GO_FUxzJR8SizRYqIhgZNA6PfRGyOhf1s7bAPNW3M9KqWRgaK07WTOYl7DzW4hpNBPA4jrl7tgsssExHpfviFL7yL52lxsmbsiLe81Z5UoM",
"size": 100446
}
}
]
}
};
function decode(string) {
return decodeURIComponent(escape(atob(string.replace(/\-/g, '+').replace(/\_/g, '/'))));
}
function getText(response) {
var result = '';
// In e.g. a plain text message, the payload is the only part.
var parts = [response.payload];
while (parts.length) {
var part = parts.shift();
if (part.parts) {
parts = parts.concat(part.parts);
}
if (part.mimeType === 'text/plain') {
// Continue to look for a 'text/html' part.
result = decode(part.body.data);
} else if (part.mimeType === 'text/html') {
// 'text/html' part found. No need to continue.
result = decode(part.body.data);
break;
}
}
return result;
}
var text = getText(response);
console.log(text);
After fighting with this for a couple of hours, I think I need to rephrase the question.
I have an object that contains and array of objects;
Playlist: [
{
"added_at": "2015-11-13T20:55:06Z",
"added_by": {
"external_urls": {
"spotify": "http://open.spotify.com/user/spotify_canada"
},
"href": "https://api.spotify.com/v1/users/spotify_canada",
"id": "spotify_canada",
"type": "user",
"uri": "spotify:user:spotify_canada"
},
"is_local": false,
"track": {
"album": {
"album_type": "album",
"available_markets": [
"CA",
"MX",
"US"
],
"external_urls": {
"spotify": "https://open.spotify.com/album/6Fr2rQkZ383FcMqFyT7yPr"
},
"href": "https://api.spotify.com/v1/albums/6Fr2rQkZ383FcMqFyT7yPr",
"id": "6Fr2rQkZ383FcMqFyT7yPr",
"images": [
{
"height": 640,
"url": "https://i.scdn.co/image/8b47495ce0c4a341f7196f70bcf4361e6257c1a0",
"width": 640
},
{
"height": 300,
"url": "https://i.scdn.co/image/da1e8958b6260e832660d0c5f3c80e9569c388c8",
"width": 300
},
{
"height": 64,
"url": "https://i.scdn.co/image/478dbfd0e579dee7392707b9a6848faff0cdfefd",
"width": 64
}
],
"name": "Purpose (Deluxe)",
"type": "album",
"uri": "spotify:album:6Fr2rQkZ383FcMqFyT7yPr"
},
"artists": [
{
"external_urls": {
"spotify": "https://open.spotify.com/artist/1uNFoZAHBGtllmzznpCI3s"
},
"href": "https://api.spotify.com/v1/artists/1uNFoZAHBGtllmzznpCI3s",
"id": "1uNFoZAHBGtllmzznpCI3s",
"name": "Justin Bieber",
"type": "artist",
"uri": "spotify:artist:1uNFoZAHBGtllmzznpCI3s"
}
],
"available_markets": [
"CA",
"MX",
"US"
],
"disc_number": 1,
"duration_ms": 205680,
"explicit": false,
"external_ids": {
"isrc": "USUM71511919"
},
"external_urls": {
"spotify": "https://open.spotify.com/track/4B0JvthVoAAuygILe3n4Bs"
},
"href": "https://api.spotify.com/v1/tracks/4B0JvthVoAAuygILe3n4Bs",
"id": "4B0JvthVoAAuygILe3n4Bs",
"name": "What Do You Mean?",
"popularity": 93,
"preview_url": "https://p.scdn.co/mp3-preview/13da79dc4803f65092d583f6e3bdf1fc4d8344e5",
"track_number": 3,
"type": "track",
"uri": "spotify:track:4B0JvthVoAAuygILe3n4Bs"
}
},
In side of each of these objects is another object I am trying to assign to scope.
So this - playlist {items [ {track {name: songname} } ] }
How do I go about assigning the track.name to scope?
Thanks!
I'm not sure if you just have a typo but why are you assigning your blank array to data.items instead of the other way around?
$scope.playListInfo = [];
$scope.getPlayList = function() {
Spotify.getPlaylistTracks('spotify_canada', '7ndCD5pklOTcrTcv4DErmI')
.then(function(data) {
var i = 0;
for(i; i < data.items.length; i++) {
var dataToKeep = {};
dataToKeep.name = data.items[i].track.name;
dataToKeep.artist = data.items[i].track.artist;
$scope.playListInfo[i] = dataToKeep;
}
});
};
Apparently, I don't have sufficient points to comment. So, I am creating this post.
The JSON data has items and not item. Also, I think you'd have to create a $scope.playlistTrack array outside the function.
$scope.playlistTrack = [];
$scope.getPlayList = function () {
Spotify.getPlaylistTracks('spotify_canada', '7ndCD5pklOTcrTcv4DErmI')
.then(function (datas) {
angular.forEach(datas, function(data){
data.items = $scope.playlistTrack;
});
});
};
Hope this answer helps.
I am getting json data from server for make the navigation menu (has the sublinks ) - for that, i am making my model as follow. is this correct..? any one help me please?
Here is the json i am getting from server:
[
{
"label": "General",
"link": "#/general",
"subLinks": [
{
"label": "Dashboard",
"link": "#/dashboard"
},
{
"label": "My Task",
"link": "#/mytask"
},
{
"label": "My Documents",
"link": "#/mydocuments"
},
{
"label": "My Templates",
"link": "#/mytemplates"
},
{
"label": "Search",
"link": "#/search"
}
]
},
{
"label": "Repositories",
"link": "#/reposotories",
"subLinks": []
},
{
"label": "SavedSearches",
"link": "#/savedSearches",
"subLinks": []
},
{
"label": "Favourites",
"link": "#/favourites",
"subLinks": []
},
{
"label": "Reports",
"link": "#/reports",
"subLinks": []
},
{
"label": "Preferences",
"link": "#/preferences",
"subLinks": []
}
]
after i receive my json i use the parse method to manipulate the models:
define(["backbone","models/model","collection/baseCollection"], function (Backbone,model,baseCollection) {
var mainLinkModel = model.extend({
defaults:{
label:"mainLink",
link:"#",
subLinks:[
label:"mainLink",
link:"#"
]
}
})
var headerCollection = baseCollection.extend({
url:function(){
return this.path + "edms/navigationLinksTest"
},
model:model,
initialize:function(){
},
parse:function(response){
var mainNavi = [];
_.each(response.navList, function(m){
// i am making new models.. but how to handle the sublinks?
mainNavi.push(new mainLinkModel(m));
})
}
});
return new headerCollection;
})
how to handle this kind of models.. any one help me in this please..?