AngularJs json URL changer - javascript

I'm working on some mega simple weather app in Angular for practice reasons and i'm stuck..
i have a angular json feed like this:
app.factory('forecast', ['$http', function($http) {
return $http.get('http://api.openweathermap.org/data/2.5/weather?q=Amsterdam,NL&lang=NL_nl&units=metric')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
and it loads the feed in to the index.html. its all working and what i wand now is a input form on index that changes the Amsterdam part of the url on js/services/forcast.js where the above code is to another city so people can see their city weather.
See the demo here: http://dev.bigstoef.nl/workspace/shiva/weer/index.html
Ive tryd about all posable options about now and i'm 3 days further and its a no go. What is there correct way here?

First, create a "configurable" service :
app.factory('forecast', ['$http', function($http) {
var city;
var cities = {
amsterdam: 'Amsterdam,NL',
paris: 'Paris,FR'
};
var api_base_url = 'http://api.openweathermap.org/data/2.5/weather';
var other_params = 'lang=NL_nl&units=metric';
return {
setCity: function(cityName){
city = cityName ;
console.log(city);
},
getWeather: function(cityName){
console.log(city);
if(cityName) this.setCity(cityName);
if (!city) throw new Error('City is not defined');
return $http.get(getURI());
}
}
function getURI(){
return api_base_url + '?' + cities[city] + '&' + other_params;
}
}]);
Then you can create a controller like the following:
app.controller('forecastCtrl', ['$scope', 'forecast',function($scope,forecast){
$scope.city = 'amsterdam' ;
$scope.$watch('city',function(){
console.log($scope.city);
forecast.setCity($scope.city);
});
$scope.getWeather = function(){
console.log('get weather');
forecast.getWeather()
.success(function(data){
console.log('success',data);
$scope.weatherData = data;
}).error(function(err){
console.log('error',err);
$scope.weatherError = err;
});
};
}]);
To implement a template as the following
<link rel="stylesheet" href="style.css" />
<div data-ng-controller="forecastCtrl">
<form>
<label>
<input type="radio" name="city" data-ng-model="city" data-ng-value="'amsterdam'">Amsterdam
</label>
<br/>
<label>
<input type="radio" name="city" data-ng-model="city" data-ng-value="'paris'">Paris
</label>
<br/>
<button data-ng-click="getWeather()">Get Weather</button>
</form>
<p class="weather-data">
{{weatherData}}
</p>
<p class="weather-error">
{{weatherError}}
</p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="script.js"></script>
You can view the code working here : http://plnkr.co/edit/rN14M8GGX62J8JDUIOl8?p=preview

You can return a function in your factory. Define your forcast as
app.factory('forecast', ['$http', function($http) {
return {
query: function(city) {
return $http.get('http://api.openweathermap.org/data/2.5/weather?q=' + city + '&lang=NL_nl&units=metric')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}
};
}]);
Then in your controller
forecast.query('Amsterdam,NL').success(function(data) {
$scope.weer = data;
});

Change service code to have a dedicated method which you can call multiple times with different parameters (cities):
app.factory('forecast', ['$http', function($http) {
return {
load: function(location) {
return $http.get('http://api.openweathermap.org/data/2.5/weather?q=' + location + '&lang=NL_nl&units=metric')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}
}
}]);
Then in controller you would be able to load forecat for other locations when you need:
forecast.load('Amsterdam,NL').then(function(data) {
$scope. weer = data;
});
Demo: http://plnkr.co/edit/GCx35VxRoko314jJ3M7r?p=preview

Related

API, angularJS, to get datas

I never done angularJS from all my life and i am lost.
So i have done this file, to obtain datas from an api with a filter of time.
forecast.js
(function() {
angular.module('application').factory('Forecast', ['$http', '$q', function($http, $q){
var ApiAddr = "api.com/";
forecast.getResults = function(timeStart, timeEnd){
// We map application varaible names with API param names
var httpParams = {
type: "global",
time: "minute",
tsmin: timeStart,
tsmax: timeEnd
};
return $http.get(apiAddr, {
params: httpParams,
cache: true
}).then(function(data){
return data;
},
function(response){
console.log(
"HTTP request "+ApiAddr+
" (with parameters tsmin="+httpParams.tsmin+", tsmax="+httpParams.tsmax+
", type="+httpParams.type+", time="+httpParams.time+
(httpParams.motive ? ", motive="+httpParams.motive : "")+
(httpParams.vector ? ", vector="+httpParams.vector : "")+
(httpParams.media ? ", media="+httpParams.media : "")+
") failed with "+response.status
);
return $q.reject(response);
}
);
}];
But i have no idea to make a controller adapter to this. What type of controller i can do ?
Every exemple are based on a fixed json file, with no parameters.
Moreover, i want, in HTML to imput the time filter, but i have totaly no idea of what to do for this. The example i have seen were to get datas, no to send.
Ps : I have made 2 days of research about this, i have never done front end programming in my life.
(function() {
angular.module('application', [])
.factory('Forecast', ['$http', '$q', function($http, $q) {
var apiaddress = 'api.com';
var forecast = {};
forecast.getResults = function(timeStart, timeEnd) {
// We map application varaible names with API param names
var httpParams = {
type: "global",
time: "minute",
tsmin: timeStart,
tsmax: timeEnd
};
return $http.get(apiaddress, {
params: httpParams,
cache: true
}).then(function(result) {
return result.data;
});
};
return forecast;
}])
.controller('SampleCtrl', ['$scope', 'Forecast', function($scope, Forecast) {
$scope.forecastReport = '';
$scope.getForecast = function() {
Forecast.getResults($scope.timeStart, $scope.timeEnd)
.then(function(report) {
$scope.result = report;
}).catch(function(err) {
$scope.result = '';
console.error('Unable to fetch forecast report: ' + err);
});
};
}]);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="application" ng-controller="SampleCtrl">
<label>Time Start:
<input type="text" ng-model="timeStart"/></label>
<label>Time End:
<input type="text" ng-model="timeEnd"/></label>
<button ng-click="getForecast()">Get Forecast</button>
<hr/>
<div>
<b>Forecast Result:</b>
</div>
<pre>{{forecastReport | json}}</pre>
</div>
Just inject the factory into your controller like this:
var app = angular.module('application');
app.controller('myController',
['$scope', 'Forecast', function($scope, Forecast) { /* access to Forecast*/}]);
Or with a component (cleaner):
app.component('myComponentCtrl', {
templateUrl: 'template.html'
controller: myComponentCtrl
})
myComponentCtrl.$inject = ['$scope', 'Forecast'];
function myComponentCtrl($scope, Forecast) {/* ... */ }

typeahead fetch data from url key and api angularjs

Hi I am new to Angularjs. I am trying to create a typeahead where I am fetching the data through the api. I tried searching for the solution but I dint get the solution what I was looking for. Below is the code what I have done so far.
HTML CODE:
<div ng-controller="newController">
<div class="selection-box">
<div class="title-box">
<div class="search_item">
<input name="document" ng-model='query' type="text" typeahead="document as document.name for document in documents | filter:query | limitTo:8" id='document' placeholder="SEARCH FOR YOUR DOCUMENT" class="search_box">
</div>
{{query}}
</div>
</div>
</div>
In this input box whatever I type it gets printed in the {{query}} but doesn't show any data fetching from the api. I am using bootstrap ui . Below is the controller what I wrote.
newController.js:
var myApp = angular.module('myModule', ['ui.bootstrap']);
myApp.service("searchService", function ($http) {
var apiUrl = "http://12.56.677/api/v1/mobile/";
var apiKey = "123nm";
this.searchDocument = function(query) {
var response = $http({
method: 'post',
url: apiUrl + "search",
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
params: {
key: apiKey,
query: query
}
});
return response;
};
});
myApp.controller('newController', ['$scope', 'searchService' , function($scope, searchService, $rootScope, $http, $window, $document) {
var apiUrl = "http://12.56.677/api/v1/mobile/";
var apiKey = "123nm";
url = apiUrl + "search";
Key = apiKey;
$scope.query = undefined;
console.log(query);
searchService.searchDocument(query='').then (function (res) {
if(res.data.status == "OK")
{
$scope.documents = res.data.result;
console.log($scope.documents);
// var userinformation = res.data.result;
// $window.localStorageService.setItem('searchDocument', JSON.stringify(query));
}
else {
$scope.errorMessage = res.data.message;
}
})
}])
Any help would be appreciated.
What you attempted to do is using typeahead with a pre-fetched list (an with an empty query).
You probably want to do asynchronous search and would need a data fetch function to do so.
HTML, note the typeahead expression:
<input name="document" ng-model='query' type="text"
typeahead="document as document.name for document in (getDocuments() | limitTo:8)"
id='document'
placeholder="SEARCH FOR YOUR DOCUMENT" class="search_box">
Controller:
myApp.controller('newController', ['$scope', 'searchService' , function($scope, searchService, $rootScope, $http, $window, $document) {
var apiUrl = "http://12.56.677/api/v1/mobile/";
var apiKey = "123nm";
// What are these two undeclared variables lying here around for?
url = apiUrl + "search";
Key = apiKey;
$scope.getDocuments = function(query){
searchService.searchDocument(query) // Check your API, I am not sure how you're API treats these parameters
.then (function (res) {
if(res.data.status == "OK")
{
var documents = res.data.result;
console.log(documents);
return documents;
}
else {
$scope.errorMessage = res.data.message;
return [];
}
})
}
}])
I think you need to return promise from the searchService.searchDocment() as below:
return searchService.searchDocument(query='').then(......)
//HTML
<input name="document"
ng-model='query' type="text"
uib-typeahead="document as document.name
for document in documents |filter:query | limitTo:8" id='document'
placeholder="SEARCH FOR YOUR DOCUMENT" class="search_box">
//Controller
searchService.searchDocument('').then (function (res) {
if(res.data.status == "OK"){
$scope.documents = res.data.result;
}
else {
$scope.errorMessage = res.data.message;
}
});

I am unable to access an asp.net mvc controller to return me a JsonResult using $resource of angular

What am I missing ? I am new to Angularjs. Trying angularjs with asp.net mvc. I am unable to access an asp.net mvc controller to return me a JsonResult using $resource of angular.
However, I get success otherwise using $.getJson of javascript but not using angularjs. What am I missing ? please guide. Thank you for replying any.
Following is my Service
EbsMvcApp.factory('classListService', function ($resource, $q)
{
var resource = $resource
(
'/Home/ClassList'
, {}
//{ method: 'Get', q: '*' }, // Query parameters
, { 'query': { method: 'GET' , isArray:false } }
);
function get($q)
{
console.log('Service: classListServic > Started');
var Defered = $q.defer();
resource.get
(
function (dataCb)
{
console.log('success in http service call');
Defered.resolve(dataCb);
}
, function (dataCb)
{
console.log('error in http service')
Defered.reject(dataCb);
}
);
return Defered.promise; // if missed, would throw an error on func: then.
};
return { get: get };
});
angular Controller:
var EbsMvcApp = angular.module('myApp', ['ngResource']);
//'classListService',
EbsMvcApp.controller
(
'myAppController',
['$scope','classListService','$q' , function ($scope, classListService, $q)
{
console.log('controller myAppController started');
var classList = classListService.get($q);
classList = classList.then(
function ()
{
(
function (response)
{
console.log('class list function response requested');
return response.data;
}
);
}
);
console.log(classList.ClassName);
console.log(classList);
console.log('end part of ctrl');
$scope.classList = classList;
$scope.SelectedClassID = 0;
$scope.message = ' message from Controller ';
}
]
);
Asp.net MVC Controller
namespace EBS_MVC.Controllers
{
public class HomeController : BaseController
{
ApplicationDbContext db = new ApplicationDbContext();
public JsonResult ClassList()
{
var List = new SelectList(db.tblClass, "ID", "ClassName");
return Json(List, JsonRequestBehavior.AllowGet);
}
}
}
Brower's response (F12):
ControllerTry1.js:11 controller myAppController started
serviceGetClassList.js:16 Service: classListServic > Started
ControllerTry1.js:28 undefined
ControllerTry1.js:29 c
ControllerTry1.js:31 end part of ctrl
angular.js:12520 Error: [$resource:badcfg]
[Browers response: screen shot][1]
Oky, finally, I got a solution using the $http service. from here
http://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2015/05/13/how-to-use-angularjs-in-asp-net-mvc-and-entity-framework-4.aspx
in csHtml file, a reference to the service.js and Controler.js is required.
I am not sure if I have added it earlier or later now. but its required.
ng-Controller:
EbsMvcApp.controller('ClassListController', function ($scope, ClassListService2) {
console.log('ClassListController Started');
GetClassList();
function GetClassList()
{
ClassListService2.GetJson()
.success(function (dataCallBack) {
$scope.classList = dataCallBack;
console.log($scope.classList);
})
.error(function (error) {
$scope.status = 'Unable to load data: ' + error.message;
console.log($scope.status);
});
}
});
ng-Service:
EbsMvcApp.factory('ClassListService2', ['$http', function ($http) {
console.log('ClassListService2 Started');
var list = {};
list.GetJson = function () {
return $http.get('/Home/ClassList');
};
return list;
}]);
csHtml View:
<div class="text-info" ng-controller="ClassListController">
<h3> Text from Controller: </h3>
#*table*#
<table class="table table-striped table-bordered">
<thead>
<tr><th>DisplayName</th><th>Value</th>
</thead>
<tbody>
<tr ng-hide="classList.length">
<td colspan="3" class="text-center">No Data</td>
</tr>
<tr ng-repeat="item in classList">
<td>{{item.Text}}</td>
<td>{{item.Value}}</td>
</tr>
</tbody>
</table>
Sorry for the delay, I just wrote up some code to quickly test the ngResource module as I haven't used it yet.
I've got the code working to do what you want using the ngResource module. I think part of the problem was that you was configuring the query method but calling the get method so your configurations was not applied.
Here is the service class that I wrote to test against a controller the same as yours.
(function () {
'use strict';
angular
.module('myApp')
.service('classService', ClassService);
ClassService.$inject = ['$resource', '$q'];
function ClassService($resource, $q) {
var resource = $resource
(
'/Home/ClassList',
{},
{
'get': { method: 'GET', isArray: true },
'query': { method: 'GET', isArray: true }
}
);
var service = {
get: get
};
return service;
////////////
function get() {
var Defered = $q.defer();
resource.get(function (dataCb) {
console.log('success in http service call');
Defered.resolve(dataCb);
}, function (dataCb) {
console.log('error in http service')
Defered.reject(dataCb);
});
return Defered.promise;
};
};
})();
The controller looks like this
(function () {
'use strict';
angular
.module('myApp')
.controller('classController', ClassController);
ClassController.$inject = ['$scope', 'classService'];
function ClassController($scope, classService) {
var vm = this;
vm.data = null;
activate();
/////////////
function activate() {
var classList = classService.get().then(function (response) {
console.log('class list function response requested');
vm.data = response;
console.log(vm.data);
});
console.log('end part of ctrl');
$scope.SelectedClassID = 0;
$scope.message = ' message from Controller ';
};
};
})();
I've included some of your original code just so you can see how it would fit in.
Glad to see you have got it working though!

angularjs $http.post with parameters

I'm new at angular and if my question is kinda low lvl dont be angry with me.
I have web service which returns sessionId and login success message if user will pass auth. for example url is that:
http://localhost:8181/login?username=USERNAME&password=12345
and here's my response:
{"sessionId":"0997cec2a8b34c84ba8419ab1204e6aa","loginSucceeded":true}
here's my login controller:
app.controller('loginCtrl', function($scope, loginService){
$scope.login=function(user){
loginService.login(user);
}
});
and here's my service:
app.factory('loginService', function($http){
return{
login: function(user){
var $promise=$http.post('http://localhost:8181/login?', user);
$promise.then(function(msg){
if(msg.loginSucceeded=="true")
console.log("opa")
else
console.log("den");
});
}
}
});
and I have user.username and user.password in my scope (using textboxes).
How can I pass those parameters in url and how can I parse that response?
In your code you're passing the username and password in the URL of the POST request. If that's what you really want (it's more common to pass them as POST data) than you can use this:
login: function(user){
var url = 'http://localhost:8181/login?username=' + user.name + '&password=' + user.password;
$http.post(url).then(function(msg){
if(msg.loginSucceeded==="true"){
console.log("opa")
}else{
console.log("den");
}
});
}
If you want to pass the data as POST data, you can pass that as the second argument in the $http.post() call:
login: function(user){
var url = 'http://localhost:8181/login';
var data = {username: user.name, password: user.password};
$http.post(url, data).then(function(msg){
if(msg.loginSucceeded==="true"){
console.log("opa")
}else{
console.log("den");
}
});
};
I never seen anyone passing login data via query string,
if you are in simple http protocol... you should consider using Basic Access Authentication or oAuth...
by the way, if you need to do what described above... this could be help you!
angular
.module('test', [])
.service('LoginService', function($q, $http) {
var self = this;
self.login = function(username, password) {
var configs = { cache: false };
var payload = {
"username" : username,
"password" : password
};
// The Method Post is generally used with a payload, but if you need to pass it as query string... you have to do:
configs.params = payload;
return $http
.post('/api/login', null /* but normally payload */, configs)
.then(function(result) {
console.log('LoginService.login:success', result);
return result.data;
})
.catch(function(error) {
console.log('LoginService.login:error', error);
return $q.reject(error);
});
;
};
})
.controller('LoginCtrl', function(LoginService, $scope) {
var vm = $scope
vm.username = 'hitmands';
vm.password = 'helloWorld';
vm.debug = 'CIAO';
vm.onFormSubmit = function(event, form) {
if(form.$invalid) {
event.preventDefault();
return;
}
vm.debug = null;
return LoginService
.login(vm.username, vm.password)
.then(function(data) { vm.debug = data; })
.catch(function(error) { vm.debug = error; })
;
};
})
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<article ng-app="test">
<div ng-controller="LoginCtrl">
<form ng-submit="onFormSubmit($event, loginForm);" name="loginForm">
<input type="text" placeholder="username" ng-model="username">
<input type="password" placeholder="Password" ng-model="password">
<div>
<button type="submit">Send Login Data</button>
</div>
<div style="color: blue; padding: 1em .5em;" ng-bind="debug | json">
</div>
</form>
</div>
</article>

Revealing module for AJAX Angular Service

Below I've got an angular app and controller where the controller have data access inside of it (bad idea, I know)
var app = angular.module('app',[]);
app.controller('HomeController',function($scope,$http){
$scope.people = null;
$scope.get = function() {
$http({
url: 'largeTestData.json',
method: 'GET'
}).then(function(data){
console.log('request successful, here is your data: ');
console.log(data['data']);
$scope.people = data['data'];
},function(reason){
console.log('this failed, this is the reason: ');
console.log(reason);
})
}
});
app.controller('ControllerWithService',function($scope, MyService){
$scope.get = MyService.get;
$scope.get(function(data){
console.log('you succeeded');
},function(reason){
console.log('you failed');
console.log(reason);
})
})
This will work in retrieving data and putting it onto the page. Knowing that having data Access in the controller is no bueno I tried to abstract that out into a service:
app.service('MyService',function($http,$q){
var get = function(){
var deferred = $q.defer();
var url = 'test.json';
$http.get(url).success(deferred.resolve).error(deferred.reject);
}
return {
get: get
}
})
Here my 'data layer' is a service that only has one method: get from the above listed URL.
app.service('MyService',function($http,$q){
var get = function(){
var deferred = $q.defer();
var url = 'test.json';
$http.get(url).success(deferred.resolve).error(deferred.reject);
}
return {
get: get
}
})
and my HTML
<body>
<script src="libs/angular-1.2.15.js"></script>
<script src="app/app.js"></script>
<script src="app/DocumentService.js"></script>
<script src="libs/jQuery-2.1.1.js"></script>
<div ng-controller="HomeController">
<button ng-click="get()" href="#">Get data</button>
<div>{{message}}</div>
<!--<div ng-repeat="p in people" >-->
<!--<b>Business Doc ID: </b><h1>{{p['busDocId']}}</h1>-->
<!--<b>DOC ID: </b>{{p['docId']}}-->
<!--<b>FILE NAME: </b><div style="color: green">{{p['fileName']}}</div>-->
<!--</div>-->
</div>
<div ng-controller="ControllerWithService">
{{message}}
<button ng-click="get()">get data</button>
<div>{{data}}</div>
</div>
</body>
I'm not getting any error messages, and the commented out out stuff in my HomeController works as expected. What am I doing wrong in trying to make my AJAX calls a service?
working solution changes:
app.service('MyService',function($http,$q){
this.get = function(){
return $http.get('test.json')
}
})
app.controller('ControllerWithService',function($scope, MyService){
$scope.data = null;
$scope.get = function() {
MyService.get().then(function (data) {
console.log('this is the success data: ');
console.log(data)
$scope.data = data;
}, function (reason) {
console.log('this is the fail reason');
console.log(reason);
$scope.data = reason;
})
}
})
It looks like it could be a couple different things. I'll post an example I have working in one of my projects right now. It should be extremely similar and simple with what you're goal is.
Service:
'use strict';
angular.module('srcApp')
.service('Getlanguage', function Getlanguage($location, $http, $log, $state, $rootScope) {
this.getContent = function() {
var language = $location.path().split('/'),
languageCulture = language[1];
if (!languageCulture) {
languageCulture = 'en';
}
$rootScope.cultureCode = languageCulture;
return $http({method: 'GET', url: '/languages/' + languageCulture + '.json'})
.error(function() {
// If service cannot find language json file, redirect to index
$state.go('lang', {lang: 'en'});
});
};
});
Controller Call to service:
After passing in the service as a dependency into the controller.
Getlanguage.getContent().then(function(res) {
$scope.content = res.data;
});
Hope this helps.

Categories