I m trying to connect my angular front end with Jenkins API.
my service.js
angular.module('jenkinsLightApp')
.factory('JenkinsService', function (CONFIG, $location, $http, $httpBackend) {
return {
getJobs: function () {
var viewParameter = 'All';
if ($location.search().view) {
// Set the value of the view query parameter
viewParameter = $location.search().view;
}
// Call Jenkins API
var promise = $http({method: 'GET', url: 'http://xx.xx.xxx.xxx:xxxx/pic/view/All/api/json'}).
then(function successCallback(response) {
alert('promise');
// Initialize jobs data
var data = response.data;
var jobs = [];
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
};
I have removed the authentication from jenkins, so angular can be able to connect.
But I have the following error:
Error: Unexpected request: GET http://xx.xx.xxx.xxx:xxxx/pic/view/All/api/json
No more request expected
$httpBackend#http://localhost:9000/bower_components/angular-mocks/angular- mocks.js:1180:1
sendReq#http://localhost:9000/bower_components/angular/angular.js:8442:1 http/serverRequest#(http://localhost:9000/bower_components/angular/angular.js:8162:16qFactory/defer/deferred.promise.then/wrappedCallbackhttp://localhost:9000/bower_components/angular/angular.js:11722:3
I have also tried to add
$httpBackend.whenGET(/pic/).passThrough();
that removed the error but I m still unable to dislplay any jenkins job in the browser.
Thanks for your help
Related
I have my controller calling the api and by the time the api returns results I have the 500 Internal server in the chrome console popping up. I am using angular 1.5.5, could you please help with some timeout code.
Tried using .timeout(3000,new Error(timeout exceeded)) before .then but it does not compile
angular.module('myApp').factory('submitService',function($http)){
var service={};
service.getJwtToken=function(user)
{
return $http({
method: "POST",
url:"http://localhost:5000/jwtTest",
data: user
}).then(function(resp){
return resp;
});
}
return service;
});
You can try with setInterval
setInterval(function () {
//Call your Service here
}, 5000);
This server error occurs because there may be missing param or something like this
//if 'function2' is dependent on any condition of 'function1' call like this
var f1 = yourService.function1(param1);
f1.then(function (data1) {
if(data1){
var f2 = yourService.function2(param2);
f2.then(function (data2) {
//Do code
});
}
});
//if 'function2' and 'function1' are independent call like this
var f1 = yourService.function1(param1);
f1.then(function (data1) {
//Do code
});
var f2 = yourService.function2(param2);
f2.then(function (data2) {
//Do code
});
To set a timeout of for the $http service, use the timeout property of the config object:
app.factory('submitService', function ($http) {
var service = {};
service.getJwtToken = function (user) {
var config = { timeout: 3000 };
return $http.post("http://localhost:5000/jwtTest", user, config);
};
return service;
});
From the Docs:
config object
Object describing the request to be made and how it should be processed. The object has following properties:
timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.
A numerical timeout or a promise returned from $timeout, will set the xhrStatus in the response to "timeout", and any other resolved promise will set it to "abort", following standard XMLHttpRequest behavior.
For more information, see
AngularJS $http Service API Reference - Arguments
I am trying to get the metadata before I perform any queries on the page, because each query is trying to get the metadata for a total of 5 times and the page is very slow. I am hoping this helps.
//version info:
var breeze = {
version: "1.5.4",
metadataVersion: "1.0.5"
};
Howevever I am getting this error:
manager.fetchMetadata(...).then(...).fail is not a function
Here is the code sample:
var manager = emProvider.createManager();
function getMetaData()
{
var deferred = $q.defer();
manager.fetchMetadata()
.then(function (data, status) {
deferred.resolve(data);
console.log('manager.fetchMetadata() success');
})
.fail(function (data, status) {
deferred.reject(data);
console.log('manager.fetchMetadata() reject');
});
return deferred.promise;
}
THis is what the createManager function looks like from the injected 'emProvider' service.
var masterManager = new breeze.EntityManager(serviceRoot + 'odata/');
// private function to create a new manager
function createManager() {
var manager = masterManager.createEmptyCopy(); // same configuration; no entities in cache.
// ... copy in some entities (e.g.,picklists) from masterManager
return manager;
}
try the following... surround all of your code blocks with anonymous self-invoking functions except for the master manager creation, comment out the getMetaData function, be sure to pick up the right adapter for your service... breeze odata configuration , make sure Q is on your js bundle at the top of your page.
breeze.config.initializeAdapterInstance("dataService", "odata");
var masterManager = new breeze.EntityManager(serviceRoot + 'odata/');
(function () {
var op = breeze.FilterQueryOp;
var query = null;
query = new breeze.EntityQuery()...
...all of your other breeze code...
masterManager.executeQuery(query).then(function (data) {...
})();
If you are using $q from AngularJS, you should use .catch instead of .fail. AngularJS uses .catch for errors in promises.
I'm trying to build a simple hybrid app with Ionic Framework.
I want to create an inifite scroll system, so I have:
.controller('DiscoverCtrl', function (uris, $scope, $cordovaToast, $http, $ionicLoading, $ionicSideMenuDelegate, $ionicScrollDelegate, $ionicPopover, localStorage, $ionicPlatform, helpers) {
var loadCircuits = function(page_to_load) {
var page_to_load = page_to_load || 1
$http.get(uris({pagination: true, per_page: 10, page: page_to_load}).circuits.discover, {timeout: 20000})
.success(function(response, status, headers, config) {
alert("success")
angular.forEach(response.circuits, function (circuit) {
$scope.cards.push(circuit);
// console.log(circuit.description)
});
$scope.next_page = response.pagination.next_page;
})
.error(function(data, status, headers, config) {
$ionicLoading.hide();
// called asynchronously if an error occurs
// or server returns response with an error status.
$cordovaToast.showLongBottom('Sory, request failed:' + status).then(function(success) {
// success
}, function (error) {
// error
});
});
}
loadCircuits();
// Load more data
$scope.loadMoreData = function() {
alert("loadMore")
loadCircuits($scope.next_page);
}
});
And:
<ion-infinite-scroll
immediate-check="false"
on-infinite="loadMoreData()"
distance="1%">
</ion-infinite-scroll>
But I'm facing the following issue:
The first time I call loadCircuits(), the success callback is triggered normally. The second time (meaning when we call $scope.loadMoreData(), the success callback is triggered before actually performing the $http.get request... And I don't understand why.
Angular Version: 1.4.3.
Thanks for your help.
$http calls are cached if they are made for same url with same parameters, so in your case it is possible that parameters haven't changed, I'd consider logging the next page.
You can also enforce not to cache with
cache: false
In $http request config
I have an AngularJS app. In this app, I'm trying to ping a REST API. This API returns a list of orders.
I need to be able to handle the scenario where I successfully GET the orders. I also need to handle the
scenario where the request to GET the orders fails. In an attempt to do this, I'm using the ngResource
module. My controller looks like the following:
myController.js
myApp.controller('myController',
function myController($scope, myService) {
myService.getOrders(function(data) {
$scope.orders = data;
});
}
);
The definition of myService is stored in myService.js. That file looks like this:
app.factory("myyService", function($resource, $log) {
return {
getOrders: function(onSuccess) {
var orders = $resource("http://localhost:1000/orders", { fetch:{method:'JSON'} });
orders.fetch(function (response) {
console.log(response);
onSuccess(response.data);
});
}
};
});
When I run this code, I get a runtime error. The error says:
TypeError: Object function g(b){z(b||{},this)} has no method 'fetch'
Maybe there has to be something I don't understand. In my mind, I see fetch defined.
The other question I have is how do I set this up to handle failed requests? Like a 404 or 502?
You forgot the curly braces after the URL parameter...
Change: http://localhost:1000/orders", { fetch :
To: http://localhost:1000/orders", {}, { fetch :
app.factory("myyService", function($resource, $log) {
return {
getOrders: function(onSuccess) {
var orders = $resource("http://localhost:1000/orders", {}, { fetch : {method:'JSON'} });
orders.fetch(function (response) {
console.log(response);
onSuccess(response.data);
});
}
};
});
[EDIT]
To handle errors from the server side, you need to set the second function in the resource call.
Example :
orders.fetch(function success() {...},
function error() {... this will execute in a http error, 400 or 500}
);
I'm just beginning to understand Angularjs and planning to build an app. I'm really a PHP programmer and have little background in javascript. Angularjs was introduced to me by a friend. I was warned that I have to also learn its Jasmine/karma testing before the functionality of the app gets bigger. So here goes, for now I have a $http post which submits an email and a password which if success return a token. Basically if success will redirect the user to the user/profile page
Controller code:
function MainCtrl($scope, $location, Api, localStorageService, Security) {
$scope.loginUser = function () {
Api.authenticatePlayer({
email : $scope.main.email,
password : $scope.main.password
}).then(function (result){
//success
$location.path('/user/profile');
}, function(result) {
//error also this will catch error 400, 401, and 500
console.log(result.data);
});
};
}
And here is my testscript:
beforeEach(function() {
module('myApp.services'),
module("myApp.controllers")
});
beforeEach(inject(function($controller, $rootScope, $location, Api, localStorageService, $httpBackend, Security) {
this.$location = $location;
this.$httpBackend = $httpBackend;
this.scope = $rootScope.$new();
this.redirect = spyOn($location, 'path');
$controller("MainCtrl", {
$scope : this.scope,
$location : $location,
localStorageService : localStorageService,
Security : Security
});
}));
describe("successfully logging in", function () {
it("should redirect you to /user/profile", function() {
//arrange
var postData = {
email : this.scope.main.email,
password : this.scope.main.password
}
this.$httpBackend.expectPOST('login', postData).respond(200);
//act
this.scope.loginUser();
this.$httpBackend.flush();
//assert
expect(this.redirect).toHaveBeenCalledWith('/user/profile');
});
});
Here is my service.js code:
return {
/**
* Authenticate player
* #param object postData Email and password of the user
* #return object
*/
authenticatePlayer: function(postData) {
return $http({
method : 'POST',
url : api + 'auth/player',
data : postData,
headers : {'Content-Type' : 'application/json'}
});
}
}
The testscript failed :(.
Here is the error:
Chrome 24.0 (Linux) controller: MainCtrl successfully logging in should redirect you to /user/profile FAILED
Error: Unexpected request: POST http://domain.com/auth/player
Expected POST login
Can anyone please help. So sorry for the trouble though.
So, this is because Api.authenticatePlayer is calling to a different path than what you are expecting.
Your test should have this instead:
this.$httpBackend.expectPOST('http://domain.com/auth/player', postData).respond(200);
Basically, in your test, $httpBackend is a mock of the code that would call your API. You get to say "When my code calls this URL, respond with _". In this code, you are saying that you expect the post to happen and to return an empty response of 200. You could replace "200" with the json payload that you want to pretend that the server responded with.