I tried the following code by coping the data from JSON link as an object. Everything was good. But when I really retrieve it remote from the server and test, it seems that I cannot get it display on the list. Can someone help ?
I want to list the title,image and author on the home.html page. Appreciate if anyone can help. Still trying to learn.
I've tried getting other JSON $http.get('https://jsonplaceholder.typicode.com/posts') and it worked. But this particular one is a little difficult for me to understand why it is not parsing correctly. For the code to work, i need to have it on my phone in order to work also. I can see the JSON being downloaded and alerted. But, I don't know why still not seeing the data.
Please see my code as follows.
http://codepen.io/ccrash/pen/VjNPkv
Home.html
<ion-view view-title="Dashboard">
<ion-content class="padding">
<h2>Ionic GET Json Example</h2>
<ion-item ng-repeat="x in result[0].data.items">
<div> {{x.title}} </div>
<div> {{x.image[0]}} </div>
<div> {{x.author}} </div>
</ion-item>
</ion-content>
</ion-view>
Controller
.controller('HomeCtrl', function($http, $scope, $ionicSideMenuDelegate) {
$http.get('http://www.malaysiakini.com/c/en/news?alt=json')
.success(function(data, status, headers,config){
//console.log('data success');
//console.log(data); // for browser console
alert(JSON.stringify(data));
$scope.result = data; // for UI
})
.error(function(data, status, headers,config){
console.log(headers);
console.log('data error');
})
.then(function(result){
things = result.data;
});
})
It's a common issue. I see errors in browser console:
It's usually because you are request to a different domain than your page is on, browser will block your request for security consideration. According to my experience, you can use jsonp as your request data type or add Access-Control-Allow-Origin headers to the server's response.
See this question for more infomation
Related
Currently in the ending stages of trying to get my app online. However using the custom domain, which is on a standard goDaddy Account, I cant view any of my tables
$http.get("https://HEROKU DOMAIN/chat").then(function (response){
$scope.chats = response.data;
});
$scope.postchat = function(chatMsg){
var data = {
chatMsg: chatMsg
};
$http.post("https://HEROKU DOMAIN/chat", JSON.stringify(data))
location.reload();
};
});
This is the AngularJs code . I've tried getting and posting from the Heroku domain, the custom domain and the dns target with no avail. Everything works on my Heroku domain, but on the custom domain no data shows up, and I cant post any data. Here is the front end html code if anyone is interested
<div class="div1">
<table class="table table2">
<tr><th>Messages</th></tr>
<tr ng-repeat="chat in chats">
<td>{{chat.chatMsg}}</td>
</tr>
</table>
Chat <input ng-model="chatMsg"/>
<button class="button button2" ng-click="postchat(chatMsg)">Send</button>
</div>
I'm not sure where to go from here, there might be some security that my custom domain has in regards to who can post and who can get from it. However, as I understand it my custom domain is merely pointing to my heroku app.
Turns out if you use http instead of https while using the custom domain everything works.
$http.get("http://CUSTOM DOMAIN/chat").then(function (response){
$scope.chats = response.data;
});
$scope.postchat = function(chatMsg){
var data = {
chatMsg: chatMsg
};
$http.post("http://CUSTOM DOMAIN/chat", JSON.stringify(data))
location.reload();
};
});
After months of working without any trouble, now when trying to make login, this error appears. The code shown is simplified, when it arrives at "Parse.User.logIn" is when the error happens. There are some similar questions here, but all of them are related to CORS, and I don´t know how or where to make something like the line below:
Access-Control-Expose-Headers: x-parse-job-status-id
CODE:
$scope.signin = function () {
var email = $scope.login.email;
var pass = $scope.login.pass;
Parse.User.logIn(email, pass, {
success: function (user) {
Stuff after successful login
}
});
},
error: function (user, error) {
stuff after unsuccessful login
}
});
}
}
Any help would be appreciated.
Fix can be found here. We tried it and worked like a charm 👍
https://github.com/parse-community/Parse-SDK-JS/issues/622
Edit:
Solution (can be found in link)
"I believe you're using the unpkg version:
https://unpkg.com/parse/dist/parse.js, and the minified production version is at https://unpkg.com/parse/dist/parse.min.js.
Which is automatically pointing to the latest release, you should use:
https://unpkg.com/parse#1.11.1/dist/parse.js
As you are now pointing to the SDK v2.0 which contains that issue."
I am building a small AngularJS project and I have encountered a problem that I want to ask you guys about.
I am using angular-local-storage module to store some data coming from my API into the browser's local storage.
In one of my controllers I assign this data to a variable in the $scope object and try to render it in the view as follows:
controller:
angular.module('Dashboard')
.controller('DashboardController',
['$scope', '$rootScope', 'localStorageService',
function ($scope, $rootScope, localStorageService) {
$scope.userData = localStorageService.get('userData');
}]);
And the view:
<div class="row">
<h4>Welcome to your dashboard <strong>{{userData.personalUserInfo.name}}</strong>!</h4>
When I log into the app (which is when the data is fetched from API and stored in local store by key 'userData'), the view is incomplete, I get only "Welcome to your dashboard !" without the name there. When I go to the dev console and look at the localStorage of my browser, the entry "userData" is there, it is just not rendered.
Then when I hit F5 and refresh the page, the name appears.
Do you have any ideas why that is and what can be done to fix that?
Cheers!
You have to use $scope.$watch for this, like following:
$scope.$watch(function() {
return localStorageService.get('userData');
}, function(newVal, oldVal) {
if (newVal !== oldVal)
$scope.userData = newVal;
})
$scope.$watch, will execute second function each time return value of first function is changed.
I'm trying to have Angular query a JSON file instead of using an http request in an Ionic project.
I'm working with the Ionic tutorial found here: https://ccoenraets.github.io/ionic-tutorial/index.html
I have gone through the entire tutorial and am "tinkering" which started with me wanting to change the data source from being an http request to a local JSON file and I've been partially successful.
All of the code I have in the project matches exactly what's seen in the tutorial with the following exception.
In the tutorial on "Module 4: Creating the Session Service," I changed this block seen in Step 3:
angular.module('starter.services', ['ngResource'])
.factory('Session', function ($resource) {
return $resource('http://localhost:5000/sessions/:sessionId');
});
To be:
angular.module('starter.services', ['ngResource'])
.factory('Session', function ($resource) {
return $resource('data/sessions.json');
});
To create the JSON file I took the return value of the http request seen in the tutorial and pasted it into the file referenced in the code and it is valid JSON.
Now, when I run the project (in a desktop browser or emulator), I am able to see the list of Sessions that was read from the JSON as expected. However, when I click/tap one of the Sessions to see the detail, the UI appears but has no data. When using the original code that gets the data via http I can see the detail.
This is the controller in my code that matches the tutorial, which presumably is where the problem lies:
.controller('SessionCtrl', function($scope, $stateParams, Session) {
$scope.session = Session.get({sessionId: $stateParams.sessionId});
})
Here is the HTML for that view:
<ion-view view-title="Session">
<ion-content>
<div class="list card">
<div class="item">
<h3>{{session.time}}</h3>
<h2>{{session.title}}</h2>
<p>{{session.speaker}}</p>
</div>
<div class="item item-body">
<p>{{session.description}}</p>
</div>
<div class="item tabs tabs-secondary tabs-icon-left">
<a class="tab-item">
<i class="icon ion-thumbsup"></i>
Like
</a>
<a class="tab-item">
<i class="icon ion-chatbox"></i>
Comment
</a>
<a class="tab-item">
<i class="icon ion-share"></i>
Share
</a>
</div>
</div>
</ion-content>
</ion-view>
Here is the error in the console after clicking through to the Session detail view:
Error: [$resource:badcfg] get
http://errors.angularjs.org/1.3.13/$resource/badcfg?p0=object&p1=array
at REGEX_STRING_REGEXP (http://localhost:8100/lib/ionic/js/ionic.bundle.js:8762:12)
at d.module.provider.$get.e.(anonymous function).q.then.p.$resolved (http://localhost:8100/lib/ionic/js/angular/angular-resource.min.js:9:330)
at processQueue (http://localhost:8100/lib/ionic/js/ionic.bundle.js:21888:27)
at http://localhost:8100/lib/ionic/js/ionic.bundle.js:21904:27
at Scope.$get.Scope.$eval (http://localhost:8100/lib/ionic/js/ionic.bundle.js:23100:28)
at Scope.$get.Scope.$digest (http://localhost:8100/lib/ionic/js/ionic.bundle.js:22916:31)
at Scope.$get.Scope.$apply (http://localhost:8100/lib/ionic/js/ionic.bundle.js:23205:24)
at done (http://localhost:8100/lib/ionic/js/ionic.bundle.js:18358:47)
at completeRequest (http://localhost:8100/lib/ionic/js/ionic.bundle.js:18548:7)
at XMLHttpRequest.requestLoaded (http://localhost:8100/lib/ionic/js/ionic.bundle.js:18489:9)
And here's the data where the Session list comes from and it's also the data I want to query:
[{"id":0,"title":"Introduction to Ionic","speaker":"CHRISTOPHE COENRAETS","time":"9:40am","room":"Ballroom A","description":"In this session, you'll learn how to build a native-like mobile application using the Ionic Framework, AngularJS, and Cordova."},{"id":1,"title":"AngularJS in 50 Minutes","speaker":"LISA SMITH","time":"10:10am","room":"Ballroom B","description":"In this session, you'll learn everything you need to know to start building next-gen JavaScript applications using AngularJS."},{"id":2,"title":"Contributing to Apache Cordova","speaker":"JOHN SMITH","time":"11:10am","room":"Ballroom A","description":"In this session, John will tell you all you need to know to start contributing to Apache Cordova and become an Open Source Rock Star."},{"id":3,"title":"Mobile Performance Techniques","speaker":"JESSICA WONG","time":"3:10Pm","room":"Ballroom B","description":"In this session, you will learn performance techniques to speed up your mobile application."},{"id":4,"title":"Building Modular Applications","speaker":"LAURA TAYLOR","time":"2:00pm","room":"Ballroom A","description":"Join Laura to learn different approaches to build modular JavaScript applications."}]
I can't seem to get my head wrapped around why changing the http request to a local file does not work for the query performed in 'SessionCtrl'.
What changes need to be made so the detail view will work?
UPDATE
Following the suggestion from #ErnestoRendon I think I have made progress.
I changed the factory to look like this:
angular.module('starter.services', ['ngResource'])
.factory('Session', function ($resource) {
return $resource('data/sessions.json',{ }, {
getData: {method:'GET', isArray: false}
});
});
And the controller has been updated to look like this:
.controller('SessionCtrl', function($scope, $stateParams, Session) {
$scope.session = Session.getData({sessionId : $stateParams.sessionId});
console.log($stateParams.sessionId); // This DOES log the correct option selected from the list
})
When leaving isArray set to false I get the same object/array error when getData() is called. When I change isArray to "true" the error goes away but no data is returned to the UI. This is the error when setting that value to "false": http://errors.angularjs.org/1.3.13/$resource/badcfg?p0=object&p1=array
In either scenario (isArray being "true" or "false") the correct sessionId will log to the console from the controller.
So while things appear to be better when setting isArray to "true," I'm still not getting data into the UI.
Here's an example that loads data from a JSON file similar to what you describe.
angular.module('starter.services', ['ngResource'])
.factory('Session', function ($resource) {
return $resource('data/sessions.json',{ }, {
getData: {method:'GET', isArray: false}
});
});
Notice that isArray is set to false.
I have a separate language json file for each partial/controller. To avoid loading all the json files at once, I have added the addPart statement in the controller instead of the module config:
$translatePartialLoader.addPart('editName');
When I browse to the partial, I see that the json file is requested from the server only when needed. But when I keep refreshing the partial by clicking the function key F5, at random times, the json file is not requested from the server and the text displayed on the view is not translated. Not sure what I can do to fix this. Any help is greatly appreciated. Here is the code:
angular.module('pp')
.controller('informationList', [
'$scope', '$rootScope', '$location', '$translatePartialLoader', '$translate',
function($scope, $rootScope, $location, $translatePartialLoader, $translate) {
$translatePartialLoader.addPart('informationList');
$translate.refresh();
}
]);
Your issue sounds similar to mine.
This (called from app config) works:
angular.module('myApp').config(function ($translateProvider, $translatePartialLoaderProvider) {
$translateProvider.useLoader('$translatePartialLoader', {
'urlTemplate': '{part}-{lang}.json'
});
$translateProvider.preferredLanguage('EN');
$translatePartialLoaderProvider.addPart('headline');
$translatePartialLoaderProvider.addPart('languages');
});
This (called from controller) does not:
angular.module('myApp').controller('Ctrl', ['$scope', '$translate', '$translatePartialLoader', function ($scope, $translate, $translatePartialLoader) {
$translatePartialLoader.addPart('headline');
$translatePartialLoader.addPart('languages');
$translate.refresh();
}]);
Here is a plunker to demonstrate the problem.
http://plnkr.co/edit/sZC2XST8BMZcMCYbgtxt?p=preview
Could you just add a
$translateProvider.use('EN');
to the config - section just right below the "preferredLanguage('EN');" - line?
This should solve your problem.
It is in in fact currently needed to define that additional line - even though it might sound a bit like "duplication" :-).