Consume API Rest from AngularJS - javascript

the purpose of this question it´s because i do not know why i can not get this done.
First i have my api in nodejs + mongodb, and using POSTMAN i can see my api on http://localhost:3000/api/.
Now in AngularJS i have my routes, i have my service calling my api but when i run it i have this error:
angular.js:11756 GET http://localhost:8080/api/platillos 404 (Not Found), i thinks it´s due to my api is on port 3000 and my web is running on port 8080, but im not sure this is the problem, this is my code:
service.js
use strict';
angular.module("nightshift")
.constant("baseURL", "/api/")
.service("menuService", ["$http", "baseURL", function($http, baseURL) {
this.getPlatillos = function() {
return $http.get(baseURL + "platillos");
}
this.getPlatillo = function(index) {
return $http.get(baseURL + "platillos/" + index);
}
}])
controllers.js
'use strict';
angular.module("nightshift")
.controller("MenuController", ["$scope", "menuService", function($scope, menuService) {
$scope.dishes = {};
menuService.getPlatillos()
.then(function(response) {
console.log("nice");
console.log(response.data);
$scope.dishes = response.data;
},
function(response) {
console.log("hola" + response.statusText);
})
}]);
my view Platillos.html
<div class = "container">
<div class = "row row-content" ng-controller = "MenuController">
<div class = "col-xs-12 col-sm-10">
<ul class = "media-list">
<li class = "media" ng-repeat = "dish in dishes">
<div class = "media-left media-middle">
<a href = "#">
<img ng-src = {{dish.image}} class = "media-object img-thumbnail">
</a>
</div>
<div class = "media-body">
<h2 class = "media-heading">{{dish.name}}
<span class = "badge">{{dish.price | currency}}</span>
</h4>
<p>{{dish.description}}</p>
</div>
</li>
</ul>
</div>
</div>
</div>
hope someone can help me

Related

Why say this error?: Error: [$compile:nonassign] Expression 'undefined' ... is non-assignable! AngularJS 1.5

I'm trying to create a component for create "Tweets" in my own website, and when I try to write something into textarea (can't write anything)
I have this image which shows the error:
And that's my code in "editorTweets.component.js":
class EditorTweetsComponentCtrl {
constructor($scope, $state, User, Tweets){
"ngInject";
this._Tweets = Tweets;
this._$state = $state;
this._$scope = $scope;
this.currentUser = User.current;
console.log(this.currentUser);
this.tweet = {
body: ''
}
}
submit() {
console.log(this.tweet.body);
}
}
let EditorTweets = {
bindings: {
tweet: '='
},
controller: EditorTweetsComponentCtrl,
templateUrl: 'components/tweets-helpers/editorTweets.html'
};
export default EditorTweets;
and the .html view:
<div class="container-editor-tweets">
<div class="left-editor-tweets">
<img ng-src="{{$ctrl.currentUser.image}}" alt="Img-User"/>
</div>
<div class="right-editor-tweets">
<div class="editor-tweet-body">
<textarea name="tweet_msg" id="tweet_msg" placeholder="Whats going on?..." ng-model="$ctrl.tweet.body"></textarea>
</div>
<div class="editor-tweet-options">
<button class="btn-submit-tweet" type="button" ng-click="$ctrl.submit()">Tweet</button>
</div>
</div>
</div>
The component shouldn't have bindings, because I don't need to send any data, so the component is trying to get "tweet" and that's the error.
This is the correct code:
let EditorTweets = {
controller: EditorTweetsComponentCtrl,
templateUrl: 'components/tweets-helpers/editorTweets.html'
};

Sharing data from API between controllers in AngularJS

I have a parent controller with some children controllers, and I want them all to share the same data that I retrieve from an Api service.
Controllers:
var app = angular.module('mymodule',[]);
app.controller('main', ['$scope', 'Api', function($scope, Api) {
var getList1 = Api.getList1()
.then(function(resp) {
$scope.list1 = resp.data;
});
var getList2 = Api.getList2()
.then(function(resp) {
$scope.list2 = resp.data;
});
}]);
app.controller('child1', ['$scope', function($scope) {
$scope.list1 = ?
$scope.list2 = ?
}]);
app.controller('child2', ['$scope', function($scope) {
$scope.list1 = ?
}]);
View:
<div ng-controller="main">
<ul>
<li ng-repeat="list in list1">
{{list.item}}
</li>
</ul>
<div ng-controller="child1">
<ul>
<li ng-repeat="list in list1">
{{list.item}}
</li>
</ul>
<ul>
<li ng-repeat="list in list2">
{{list.item}}
</li>
</ul>
</div>
<div ng-controller="child1">
<ul>
<li ng-repeat="list in list1">
{{list.item}}
</li>
</ul>
</div>
</div>
I tried to use this solution with Angular’s events mechanism ($on, $emit).
The problem was that I had to figure out which child controller is active and send the data when the promise has resolved. It ends with ugly spaghetti code...
Well, the best way is to use a service to have your API handling atomar placed inside your application. This fiddle shows you how you could achieve what you try to. By using AngularJS services you will be able to share the same data, objects and functions between controllers and let them interact with eachother. This is undepending on the amount of your controllers inside your application.
The following example is a full working API service with real HTTP-Requests and a real AngularJS service handling. It will help you by implement such logic inside your application. Please dont forget to check out the fiddle demo.
View
<div ng-controller="MyCtrl">
<h1>
MyCtrl
</h1>
<button ng-click="clearData()">
Clear data by using MyCtrl
</button>
<div ng-repeat="user in users">
<p>
Username: {{ user.name }}
</p>
</div>
</div>
<br /><br />
<div ng-controller="MyOtherCtrl">
<h1>
MyOtherController
</h1>
<button ng-click="clearData()">
Clear data by using MyOtherController
</button>
<div ng-repeat="user in users">
<p>
Username: {{ user.name }}
</p>
</div>
</div>
AngularJS Application
var myApp = angular.module('myApp',[]);;
myApp.controller('MyCtrl', function ($scope, apiService) {
$scope.users = apiService.getResponseData();
$scope.$watch(function () { return apiService.getResponseData()}, function (newValue, oldValue) {
$scope.users = newValue
});
$scope.clearData = function () {
apiService.reset();
}
});
myApp.controller('MyOtherCtrl', function ($scope, apiService) {
apiService.loadData();
$scope.$watch(function () { return apiService.getResponseData()}, function (newValue, oldValue) {
$scope.users = newValue
});
$scope.clearData = function () {
apiService.reset();
}
})
myApp.service('apiService', function ($http) {
var responseData = null;
return {
loadData: function () {
return $http({
url: 'https://jsonplaceholder.typicode.com/users',
method: 'GET'
}).then(function (response) {
responseData = response.data
});
},
getResponseData: function () {
return responseData
},
reset: function () {
responseData = null;
}
}
});
As your data is in the scope of the parent controller, you can access it in children controllers with $scope.$parent:
app.controller('child1', ['$scope', function($scope) {
$scope.list1 = $scope.$parent.list1;
$scope.list2 = $scope.$parent.list2;
}]);
Write your children as directives, and then you can inject data on the scope.
yourModule.directive('child1', function() {
return {
scope: {list1:'=',
controller: function (scope) {
//not sure you even need a controller, but it might look like this
scope.doSomething = function() {
//access scope.list1 here
}
},
template: '<ul><li ng-repeat="list in list1">{{list.item}}<li><ul>'
}
}
Usage:
<child1 list1="list1"></child1>

Expected Array but received ...(JSON)... AngularJS Error

I'm learning Angular1 from Adam Freeman's ,,Pro AngularJS" book. I've got a problem with building a DeployD app he's describing in chapters 6-8 - it seems like my code doesn't want to read JSON
That's my HTML:
<!DOCTYPE html>
<html ng-app="sportsStore" lang="pl">
<head>
<title>SportsStore</title>
<script src="components/angular.js"></script>
<script src="components/angular-resource.js"></script>
<link href="components/bootstrap.css" rel="stylesheet" />
<link href="components/bootstrap-theme.css" rel="stylesheet" />
<script>
angular.module("sportsStore", ["customFilters"]);
</script>
<script src="controllers/sportsStore.js"></script>
<script src="filters/customFilters.js"></script>
<script src="controllers/productListControllers.js"></script>
</head>
<body ng-controller="sportsStoreCtrl">
<div class="navbar navbar-inverse">
<a class="navbar-brand" href="#">SKLEP SPORTOWY</a>
</div>
<div class="panel panel-default row" ng-controller="productListCtrl">
<div class="alert alert-danger" ng-show="data.error">
Błąd ({{data.error.status}}). Dane produktu nie zostały wczytane.
Kliknij tutaj, aby spróbować ponownie
</div>
<div class="panel panel-default row" ng-controller="productListCtrl"
ng-hide="data.error">
<div class="col-xs-3">
<a ng-click="selectCategory()"
class="btn btn-block btn-default btn-lg">Strona główna</a>
<a ng-repeat="item in data.products | orderBy:'category' |
unique:'category'" ng-click="selectCategory(item)" class=" btn btn-block
btn-default btn-lg" ng-class="getCategoryClass(item)">
{{item}}
</a>
</div>
<div class="col-xs-8">
<div class="well"
ng-repeat="item in data.products | filter:categoryFilterFn |
range:selectedPage:pageSize">
<h3>
<strong>{{item.name}}</strong>
<span class="pull-right label label-primary">
{{item.price | currency}}
</span>
</h3>
<span class="lead">{{item.description}}</span>
</div>
<div class="pull-right btn-group">
<a ng-repeat="page in data.products | filter:categoryFilterFn |
pageCount:pageSize" ng-click="selectPage($index + 1)" class="btn
btn-default" ng-class="getPageClass($index + 1)">
{{$index + 1}}
</a>
</div>
</div>
</div>
</body>
</html>
and the sportStore.js controller
angular.module("sportsStore")
.constant("dataUrl", "http://localhost:5500/products")
.controller("sportsStoreCtrl", function ($scope, $http, dataUrl) {
$scope.data = {};
$http.get(dataUrl)
.then(function (data) {
$scope.data.products = data;
},
function (error) {
$scope.data.error = error;
});
});
I'm using DeployD to build an API, and the problem is that when I try to run my app, the error shows up in console:
Error: [filter:notarray] Expected array but received:
{"data":[{"name":"Kajak","description":"Łódka przeznaczona dla jednej
osoby","category":"Sporty
Wodne","price":275,"id":"d9b9e4fcb9df3853"},{"name":"Kamizelka
ratunkowa","description":"Chroni i dodaje uroku","category":"Sporty
wodne","price":49.75,"id":"3c1cceedb44ddb84"},{"name":"Piłka","description":"Zatwierdzona
przez FIFA rozmiar i waga","category":"Piłka
Nożna","price":19.5,"id":"447a2079a8488932"},{"name":"Flagi
narożne","description":"Nadadzą Twojemu boisku profesjonalny
wygląd","category":"Piłka
Nożna","price":34.95,"id":"2b2dd597f18bb8a7"},{"name":"Stadion","description":"Składany
stadion na 35000 osób","category":"Piłka
Nożna","price":79500,"id":"2cfe0f6767240bf9"},{"name":"Czapka","description":"Zwiększa
efektywność mózgu o
75%","category":"Szachy","price":16,"id":"dfc137db43574b4a"},{"name":"Niestabilne
krzesło","description":"Zmniejsza szansę
przeciwnika","category":"Szachy","price":29,"id":"e2b644c5091d28ca"},{"name":"Ludzka
szachownica","description":"Przyjemna gra dla całej
rodziny","category":"Szachy","price":75,"id":"f945806bb011895d"},{"name":"Błyszczący
król","description":"Pokryty złotem i wysadzany diamentami
król","category":"Szachy","price":1200,"id":"fab242704bb38b64"}],"status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://localhost:5500/products","headers":{"Accept":"application/json,
text/plain, /"}},"statusText":"OK"}
http://errors.angularjs.org/1.6.0-rc.1/filter/notarray?p0=%7B%22data%22%3A%…son%2C%20text%2Fplain%2C%20*%2F*%22%7D%7D%2C%22statusText%22%3A%22OK%22%7D
at angular.js:68
at angular.js:20392
at fn (eval at compile (angular.js:15095), :4:388)
at regularInterceptedExpression (angular.js:16203)
at Scope.$digest (angular.js:17732)
at Scope.$apply (angular.js:18006)
at done (angular.js:12150)
at completeRequest (angular.js:12376)
at XMLHttpRequest.requestLoaded (angular.js:12304)
I tried to skim through similar errors on SO but none of the solutions seemed to work for me. Did someone have a similar problem?
ng repeat works with an arrays but as per the response getting from the API in then() method is not the data itself but it is having a property named as data which is the actual array that you have to pass in ng-repeat.
So, instead of using $scope.data.products = data use $scope.data.products = data.data
----------OR----------
.then(function (response) {
$scope.data.products = response.data;
}
The error message shows the filter refusing to process the response object instead of the data array. Expected array but received: {data:[..., headers: ...
The .then method of the $http service returns a response object, not data.
angular.module("sportsStore")
.constant("dataUrl", "http://localhost:5500/products")
.controller("sportsStoreCtrl", function ($scope, $http, dataUrl) {
$scope.data = {};
$http.get(dataUrl)
//.then(function (data) {
// $scope.data.products = data;
.then(function (response) {
$scope.data.products = response.data;
},
function (error) {
$scope.data.error = error;
});
});
Data is only one property of the response object:
$http(...).
then(function onSuccess(response) {
// Handle success
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
}, function onError(response) {
// Handle error
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
});
ng repeat and filter works with array, you need to access the data
angular.module("sportsStore")
.constant("dataUrl", "http://localhost:5500/products")
.controller("sportsStoreCtrl", function ($scope, $http, dataUrl) {
$scope.data = {};
$http.get(dataUrl)
.then(function (data) {
$scope.data.products = data.data;
},
function (error) {
$scope.data.error = error;
});
});
Angular expects the data variable to be type of array.
$scope.data = [];
Then try following code:
$http.get('dataUrl')
.success(function(data) {
$scope.data = data;
}).error(function(data, status) {
$log.error('Error ' + status + ' unable to get data from server.');
});
Also remember to add to your controller the $log to properly display bugs in console:
.controller('sportsStoreCtrl', ['$scope', '$http', '$log', function ($scope, $http, $log)

Angularjs : Print object from control to view with ionic

I try to build new APP with ionic framework and Angularjs.
Now my problem is i cannot show the result from controller to view. I try open console.log(allposts); in my browser ans we show the result good.
But in view its not show any thing
allpost.html
<dive class="item itemfull" ng-repeat="post in allpost">
<div class="item item-body">
<div>{{ post.title }}
<div class="title-news"><div class="title" ng-bind-html="post.content"></div></div>
</div>
</div>
</div>
And the controller
myApp.controller('allpost', function($scope , $http , $stateParams , Allposts) {
var id = $stateParams.id;
$scope.post = Allposts.GetAllposts(id);
});
myApp.factory('Allposts',['$http', '$q',function($http,$q){
var allposts = [];
var pages = null;
return {
GetAllposts: function (id) {
return $http.get("http://kotshgfx.info/azkarserv/?json=get_category_posts&id="+id+"&status=publish",{params: null}).then(function (response) {
items = response.data.posts;
allposts = items;
console.log(allposts);
return items;
$ionicLoading.hide();
});
}
}
}]);
Where is error ?
try to change the code like this in controller and factory in js files
.controller('allpost', function ($scope, $http, $stateParams, Allposts) {
var id = $stateParams.id;
Allposts.GetAllposts(id).then(
function (response) {
$scope.allPosts = response.data.posts;
});
})
.factory('Allposts', ['$http', '$q', function ($http, $q) {
return {
GetAllposts: function (id) {
return $http.get("http://kotshgfx.info/azkarserv/?json=get_category_posts&id=" +
id + "&status=publish");
}
}
}]);
the html file
<div class="item itemfull" ng-repeat="post in allPosts">
<div class="item item-body">
<div>{{ post.title }}
<div class="title-news">
<div class="title" ng-bind-html="post.content"></div>
</div>
</div>
</div>
</div>
It works for my test

AngularJS with UI-Route and Master Detail

I'm trying to get JSON data from my server and display them into my website. I am using Ui-router extension. What I am looking for here is a master-detail setup.
Index.html
<input ng-model="manga.name" ng-change="searchManga()" id="search" type="search" placeholder="Manga İsmi Girin..." required>
<div class="row" ui-view="viewA">
<div class="col s8 offset-s1" ng-controller = "nbgCtrl">
<div class="row">
<div class="col s12 m6 l4" ng-repeat = "manga in mangas">
<div class="row">
<div class="col s5">
<a ui-sref="ui-sref="#/manga/{{manga.id}}"" class="thumbnail">
<img src="/kapaklar/{{manga.kapak}}">
</a>
</div>
<div class="col s7">
<p>{{manga.ad}}</p>
<a href="" class="waves-effect waves-light btn">
</a>
I have above a main page and repeating some thumbnails. Every thumbnail links to its detailed information page. And when clicking a thumbnail it has to carry its own data and load it here. Here's what I've got so far:
JS:
angular.module('nasuh',["ui.router"])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('list', {
url: "/",
controller: "ListCtrl",
templateUrl: "index.html",
}
)
$stateProvider
.state('icerik', {
url: "/icerik/:{{mangaid}}",
controller: "mmgCtrl",
views: {
"viewA": { templateUrl: "icerik.html" },
}
}
)
})
.factory('Mangas', function($http){
var factory = {};
function getData(manganame, callbak) {
var url = '/uzak/remote.php?callback=JSON_CALLBACK';
$http.get(url).success(function(data){
factory = data.results;
callback(data.results);
})
}
return {
list: getData,
find: function(name, callback) {
console.log(name);
var manga = cachedData.filter(function(entry) {
return entry.id == name;
})[0];
callback(manga);
}
};
})
.controller('ListCtrl', function($scope, $http, Mangas) {
$scope.manga = {
name: '' }
$scope.searchManga = function() {
Mangas.list($scope.manga.name, function(mangas) {
$scope.mangas = mangas;
});
}
})
.controller('mmgCtrl', function($scope, $http, $stateParams, Mangas) {
Mangas.find($stateParams.mangaid, function(manga) {
$scope.manga = manga;
});
})
I just doubt that the getData is not a promise in resolve closure you hava returned MY.isimler.then so in mmgCtrl controller first console getData to make sure it's a promise or data

Categories

Resources