How to request API data with $http service - javascript

I'm developing an app with Riot Games API but this example it's done with REST Countries API. https://restcountries.eu/rest/v1/alpha/co
I use a MEAN.IO stack and this is my code:
test.html
<html ng-app="lolData">
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.indigo-pink.min.css">
<script defer src="https://code.getmdl.io/1.1.3/material.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<section id="center" ng-controller="summonerStats">
<form ng-submit="search()">
<div class="mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" type="text" id="summonerName" placeholder="Summoner Name">
<label class="mdl-textfield__label" for="sample1"></label>
</div>
<input class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" type="submit" value="Search"/>
<p ng-show="show">
{{ mystats.name }}
</p>
</form>
</section>
</body>
</html>
test.js
'use strict';
var lolData = angular.module('lolData', []);
console.log("before controller");
lolData.controller('summonerStats', function($scope, $http) {
var url = "https://restcountries.eu/rest/v1/alpha/co";
console.log("inside controller");
$scope.show = false;
$scope.search = function() {
$http.get(url)
.success(function(response) {
$scope.mystats = response;
$scope.show = true;
console.log("inside success controller");
});
};
});
When I refresh the page the code is executed until "before controller" console.log. It can't get inside lolData.controller. And in the browser console displays the following error.
And html doesn't accept the embeded javascript scope.
What am I missing?
Update 1:
I added the index.html in a codepen: Index.html
And Header.html in a codepen too: header.html

Not sure if this is your problem, but $http.success (and $http.error) has been depreciated since v1.4.4. Instead, use callback functions for success and error
var url = "https://restcountries.eu/rest/v1/alpha/co";
$http.get(url).then(
function successCallback(response) {
$scope.mystats = response;
$scope.show = true;
console.log("inside success controller");
}, function errorCallback(error) {
console.log(error);
});

Your response object doesn't do what you think it does.
From angular's docs you see the response has multiple properties attached to the returned object.
You want
$scope.mystats = JSON.parse(response.data);

Related

Why doesn't angular load in this plnkr?

I have researched my issue and tried many solutions but have not solved it.
For some reason angular does not seem to be loading in plunker.
I have head iffy are no longer supported in later version in angular, but I have tried loading an older version and still does not work.
Any ideas on how I can get this running?
Here is the link:
http://plnkr.co/edit/rrnzNjze2QqkWtjvNUNH?p=preview
HTML
<!DOCTYPE html>
<html ng-app="githubViewer">
<head>
<script data-require="angular.js#*" data-semver="1.1.0" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.0/angular-bootstrap-prettify.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<h1>{{message}}</h1>
<div>
{{ error }}
</div>
<div>
<div>
Name: {{user.name}}
</div>
<div>
Location: {{user.location}}
</div>
<div>
<img ng-src="{{user.avatar_url}}" title="{{user.name}}" />
</div>
</div>
</body>
</html>
Javascript
// Code goes here
var app = angular.module("githubViewer", []);
var MainController = function($scope, $http) {
var onUserComplete = function(response){
$scope.user = response.data;
};
var onError = function(reason){
$scope.error = "Could not fetch the user request!";
};
$http.get("https://api.github.com/users/robconery")
.then(onUserComplete, onError);
$scope.message = "Hello, Angular!";
};
app.controller("MainController", ["$scope", "$http", MainController]);
Replace angular-bootstrap-prettify.js (I don't know what is angular-bootstrap-prettify, do you really need it?) by angular.js and your plunkr works.

Beginners help to Angular JS debugging via console errors

AngularJS is new to me (and difficult). So I would like to learn how to debug.
Currently I'm following a course and messed something up. Would like to know how to interpret the console error and solve the bug.
plnkr.co code
index.html
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<h1>{{message}}</h1>
{{ username }}
<form action="searchUser" ng-submit="search(username)">
<input type="search"
required placeholder="Username to find"
ng-model="username"/>
<input type="submit" value="search">
</form>
<div>
<p>Username found: {{user.name + error}}</p>
<img ng-src="http://www.gravatar.com/avatar/{{user.gravatar_id}}" title="{{user.name}}"/>
</div>
</body>
</html>
script.js
(function() {
var app = angular.module("githubViewer", []);
var MainController = function($scope, $http) {
var onUserComplete = function(response) {
$scope.user = response.data;
};
var onError = function(reason) {
$scope.error = "could not fetch data";
};
$scope.search = function(username) {
$http.get("https://api.github.com/users/" + username)
.then(onUserComplete, onError);
};
$scope.username = "angular";
$scope.message = "GitHub Viewer"; };
app.controller("MainController", MainController);
}());
The console only says
searchUser:1 GET http://run.plnkr.co/lZX5It1qGRq2JGHL/searchUser? 404
(Not Found)
Any help would be appreciated.
In your form, action you have written this
<form action="searchUser"
What this does is it will try to submit to a url with currentHostName\searchUser, so in this case your are testing on plunker hence the plunker url.
You can change the url where the form is submitted. Incase you want to search ajax wise then you dont even need to specify the action part. You can let your service/factory make that call for you.
Though not exactly related to debugging this particular error, there is a chrome extension "ng-inspector" which is very useful for angularJS newbies. You can view the value each of your angular variable scopewise and their value. Hope it helps!
Here is the link of the chrome extension: https://chrome.google.com/webstore/detail/ng-inspector-for-angularj/aadgmnobpdmgmigaicncghmmoeflnamj?hl=en
Since you are using ng-submit page is being redirected before the response arrives and you provided any action URL as searchUser which is not a state or any html file so it being used to unknown address, it is async call so it will take some time you can use input types as button instead of submit.
Here is the working plunker.
<!DOCTYPE html>
<html ng-app="githubViewer">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<h1>{{message}}</h1>
{{ username }}
<form >
<input type="search"
required placeholder="Username to find"
ng-model="username"/>
<input type="button" ng-click="search(username)" value="search">
</form>
<div>
<p>Username found: {{user.name + error}} {{user}}</p>
<img ng-src="http://www.gravatar.com/avatar/{{user.gravatar_id}}" title="{{user.name}}"/>
</div>
</body>
</html>

Issues with AngularJS $http-Service

The following code should fetch data from a MySQL Database with a $http-service but somehow the data, which the service provides doesn´t go to the controller/gets displayed wrong :/. If I start my application a empty or wrong table gets displayed at my page.
I provided some sampledata in the getUsers() function. The PHP code, which provides the data is working and this is a example of the JSON the PHP returns.
Maybe you guys can help me out to fix this up.
var app = angular.module('DBapp', []);
app.controller('MainCtrl', function($scope, $http, DatabaseService) {
$scope.userData = DatabaseService.getUsers();
});
app.factory('DatabaseService', function($http) {
var srv = {};
//Service Implementation
srv.getUsers = function() {
return [{"user_id":"1","firstname":"Barrack","lastname":"Obama","email":"obama#web.de"}, {"user_id":"2","firstname":"Tom","lastname":"Hanks","email":"tommy#web.de"},{"user_id":"6","firstname":"Felix","lastname":"Blume","email":"felix.b#selfmade.de"}];
};
//I provided some dummy-data in the getUsers-function as example output from the DB
//Public API
return {
getUsers: function() {
return srv.getUsers();
}
};
});
<!DOCTYPE html>
<html ng-app="DBapp">
<head>
<meta charset="ISO-8859-1">
<title>DB Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body ng-controller="MainCtrl">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div>
<div>
<div class="page-header">
<h1>Overview Database</h1>
</div>
<table style="font-size:20px; margin-left:10px;" class="table table-hover"">
<thead><tr><th>ID</th><th>Firstname</th><th>Secondname</th><th>Email</th></tr></thead>
<tbody>
<tr ng-repeat="user in userData">
<td ng-bind="user.user_id"></td>
<td ng-bind="user.firstname"></td>
<td ng-bind="user.lastname"></td>
<td ng-bind="user.email"></td>
<td>
<a ng-href="#/database/{{ user.user_id }}/edit"><button type="button" class="btn btn-info"><span class="glyphicon glyphicon-wrench"></span> Edit</button></a>
</td>
<td> <a ng-href="#/database/{{ user.user_id }}/delete"><button type="button" class="btn btn-danger"><span class="glyphicon glyphicon-trash"></span> Delete</button></a></td>
</tr>
</tbody>
</table>
<add-user-form></add-user-form>
</div>
</div>
</div>
</div>
<!-- SCRIPTS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src=lib/jquery/jquery-1.10.2.min.js></script>
<script src=lib/angular/angular.js></script>
<script src=lib/angular-route/angular-route.js></script>
<script src=scripts/app.js></script>
<script src=scripts/services/db_service.js></script>
<script src=scripts/controllers/main_controller.js></script>
<script src=scripts/directive/addUser_form.js></script>
<script src=scripts/controllers/delete_controller.js></script>
<script src=scripts/controllers/edit_controller.js></script>
</body>
</html>
As you can see above, it works with the dummy data. But if I change my service to the following code (with the actual $http-request) nothing works...
So the question is:
How do I pass my data from the http request to the $scope in the MainCtrl ?
app.factory('DatabaseService', function($http) {
var srv = {};
//Service Implementation
srv.getUsers = function() {
$http.post("php/getData.php").success(function(data) {
return data;
});
};
//Public API
return {
getUsers: function() {
return srv.getUsers();
}
};
});
`
It probably will work if you just return the array from your service like
return {
getUsers: function() {
return srv.getUsers;
}
};
The function call you used is not possible.
Ok here comes part 2:
I had no chance to test it, but it should work.
app.factory('DatabaseService', function($http) {
var srv = {};
//Service Implementation
$http.post("php/getData.php").success(function(data) {
srv.users = data;
});
//Public API
return {
getUsers: function() {
return srv.users;
}
};
});
Jorg is right, this part 2 was a hasty reaction, sorry. To return the promise is a possible solution, return $http.post("php/getDat.php"), and than in your controller add the success function
DatabaseService.getUsers().success(function(data) {
$scope.userData = data;
});
Hope that helps

Controller not a function got undefined error message angular js

I am a beginner with MEAN Stack development. I was trying out to play around with some angular stuff but got completely messed up the the controllers.
Here is my main html file
<!--main.html-->
<html>
<head>
<title>Chirp</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="javascripts/chirpApp.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="stylesheets/style.css">
</head>
<body ng-app="chirpApp">
<div id='main' class="container" ng-controller="mainController">
<div class="col-md-offset-2 col-md-8">
<div class="clearfix">
<form ng-Submit="post()">
<input required type="text" class="form-control" placeholder="Your name" ng-model="newPost.created_by" />
<textarea required class="form-control" maxlength="200" rows="3" placeholder="Say something" ng-model="newPost.text"></textarea>
<input class="btn submit-btn pull-right" type="submit" value="Chirp!" />
</form>
<div id="post-stream">
<h4>Chirp Feed</h4>
<div class="post" ng-repeat="post in posts | orderBy:'created_at':true" ng-class-odd="'odd'" ng-class-even="'even'">
<p>{{post.text}}</p>
<small>Posted by #{{post.created_by}}</small>
<small class="pull-right">{{post.created_at | date:"h:mma 'on' MMM d, y"}}</small>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
I have created another html file for registration. here is the code for it.
<!--register.html-->
<html>
<head>
<title>Chirp</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="javascripts/chirpApp.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="stylesheets/style.css">
</head>
<body ng-app="chirpApp">
<div id='main' class="container" ng-controller="authController">
<form class="form-auth" ng-submit="register()">
<h2>Register</h2>
<p class="text-warning">{{error_message}}</p>
<input type="username" ng-model="user.username" placeholder="Username" class="form-control"><br>
<input type="password" ng-model="user.password" placeholder="Password" class="form-control"><br>
<input type="submit" value="Register" class="btn btn-primary" />
</form>
</div>
</body>
</html>
I have created two separate controllers for registration and posts. the first controller works nicely but whenever I am trying to add a second controller I am getting an error message. Here is the code for my controllers.
//chirpApp.js
var app = angular.module('chirpApp', []);
app.controller('mainController', function($scope){
$scope.posts = [];
$scope.newPost = {created_by: '', text: '', created_at: ''};
$scope.post = function(){
$scope.newPost.created_at = Date.now();
$scope.posts.push($scope.newPost);
$scope.newPost = {created_by: '', text: '', created_at: ''};
};
});
app.controller('authController', function($scope){
$scope.user = {username: '', password: ''};
$scope.error_message = '';
$scope.login = function(){
//placeholder until authentication is implemented
$scope.error_message = 'login request for ' + $scope.user.username;
};
$scope.register = function(){
//placeholder until authentication is implemented
$scope.error_message = 'registeration request for ' + $scope.user.username;
};
});
I am getting the following error in the chrome console :
Error: [ng:areq] http://errors.angularjs.org/undefined/ng/areq?p0=authController&p1=not%20a%20function%2C%20got%20undefined
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:6:453
at tb (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:18:250)
at Oa (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:18:337)
at $get (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:61:288)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:48:476
at q (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:7:367)
at S (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:48:342)
at h (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:43:59)
at h (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:43:76)
main.html works fine and the data is being binded successfully.
The issue is with the register.html page. I suppose the authController is not getting binded
Can anyone suggest me the best way of implementing the same? And why the controller is getting undefined?
Try the following checklist:
angularjs lib is included in
ng-app=".." directive is in index.html
..path/to/module and other controllers in index.html
module and controllers defined correctly (spelling, syntax etc)
Controller example (if not using global angular var:
app.controller('AppController', ['$http', '$scope', '$log',
function($http, $scope, $log) {
// TODO: implement
}
]);
Hope this helps.
Here is the plunker of your files
http://embed.plnkr.co/6jNXImBddYqjK23FCWUy/preview
Your application works as expected. Please check your core files is loaded or not.
Hope this helps
your code
When you create a new controller with the AngularJS Controller Sub-Generator you have to reboot Grunt.

Angular URL 'trustAsResourceUrl' not working

I'm using angular-file-upload.js and uploading an image. When the upload is successful, it returns a URL to where the image is hosted, which is hosted as a blob on Azure.
The upload is successful, and the URL is returned correctly, however when I push this URL on an "images" stack to view this image in the browser, it won't work properly. For example, the URL I get back looks like this:
"https://searlesmedia.blob.core.windows.net/event-images/4_slide-archive.jpg"
Controller.js
uploader.onSuccessItem = function (fileItem, response, status, headers) {
console.info('onSuccessItem', fileItem, response, status, headers);
$scope.uploadcomplete = "Upload Successful";
var url = $sce.trustAsResourceUrl(response);
$scope.images.push(url);
};
Html
<div class="row" data-ng-repeat="image in images">
<img ng-src="{{image}}" class="img-responsive" />
</div>
Hi it looks like you miss something please see here: http://plnkr.co/edit/1PpscI4dOMYpYRf6fbUS?p=preview
angular.module('mySceApp', ['ngSanitize'])
.controller('AppController', ['$http', '$scope', '$sce',
function($http, $scope, $sce) {
$scope.image = {};
$http.get("test_data.json").success(function(data) {
console.log(data.url);
// $scope.userComments = userComments;
$scope.image.url = $sce.trustAsResourceUrl(data.url);
});
}
]);
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example64-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.16/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.16/angular-sanitize.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="mySceApp">
<div ng-controller="AppController as myCtrl">
<div class="well">
<b>{{userComments.name}}</b>:
<img ng-src="{{image.url}}">
<br>
</div>
</div>
</body>
</html>

Categories