I'm new to AngularJS, so please, bear with me. I got the following code:
var testModule = angular.module("testModule", ['ngResource']);
testModule.config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
'self',
'https://api.twitter.com/**']);
});
testModule.controller("SecondController",
function SecondController($scope, $resource){
$scope.secondField = "Hello World";
try{
var restClient =
//$resource("https://api.github.com/repos/angular/angular.js/issues", [],
$resource("https://api.twitter.com/1.1/search/tweets.json", [],
{
"get":{method:"GET", headers:{"Accept":"application/json"},
interceptor: {
"response":function(data){
alert("Response: " + data);
},
"responseError":function(data){
alert("Error: " + data);
}
}
}
});
$scope.about = restClient.get();
} catch(err) {
$scope.error = err.message;
}
$scope.done = true;
}
);
It's supposed to execute the responseError function and data.status should be equal to 215 (the request requires authentication to pass successfully). Instead, the response code is 0.
I'm actually trying to reach a different API (that does not require authentication), but the status code is also 0 and I don't really have any idea what the issue might be. The only successful request I could execute till now is:
GET https://api.github.com/repos/angular/angular.js/issues
Executed by $resource.query(). But nor twitter, nor the target API can be reached. I hope providing me a solution for the twitter example can help me solve my issue.
Thanks.
Edit: Using AngularJS 1.2.0 rc2
This may be because of cross domain request. Status code 0 will come when you try to access web service of different domain. In this case you need to use JSONP as method in ngResource.
http://docs.angularjs.org/api/ngResource.$resource
Related
how can i handle a jsonp response? i tried to search but i cant solve it. the screen shot below shows a jsonp result.1
i get that jsonp response using this code, services.js
var app=angular.module('F1FeederApp.services', []);
app.config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
'self',
'http://ergast.com/**'
]);
});
app.factory('ergastAPIservice', function($http) {
var ergastAPI = {};
var urlFiltered = 'http://ergast.com/api/f1/current/driverStandings.json';
ergastAPI.getDrivers = function() {
return $http({
method: 'JSONP',
url: urlFiltered
});
}
return ergastAPI;
});
now, i access it using the code below and gives me result on the 1st picture.
angular.module('F1FeederApp.controllers', []).
controller('driversController', function($scope, ergastAPIservice) {
$scope.nameFilter = null;
$scope.driversList = [];
// //ergastAPIservice.getDrivers() ->> when i try this i get error this is not a function.
//ergastAPIservice.getDrivers().success(function (response) {
//Dig into the responde to get the relevant data
// $scope.driversList = response.MRData.StandingsTable.StandingsLists[0].DriverStandings;
//});
//code above doesnt work so i tried to access it or atleast show a value like
// the code below
console.log(ergastAPIservice.getDrivers());
console.log(ergastAPIservice.getDrivers().MRData.StandingsTable.StandingsLists[0].DriverStandings);
});
now i get the 1st picture using console.log(jsonp response).
how can i get the list of drivers in that response?,
like: collectionVar = response.getDrivers();.
any link or same problem links would help thanks!
Do something like this. This should work . You are getting a promise . Promises are handled like below. Learn more about promise
app.controller("testController", function($scope,testService){
testService.getDrivers ()
.then(function (response) {
$scope.standingTable = response.data.MRData.StandingsTable.StandingsLists[0].DriverStandings;
// handle valid reponse
},
function(error) {
//handel error
});
}
Big thanks for Noman! i didnt know that i was getting a angular promise response at first. though i want to get the driver standing list. so i use this code.
$scope.driversList = response.data.MRData.StandingsTable.StandingsLists[0].DriverStandings;
I amtrying to call Google Tasks API for a app I'm building.When I make the call using Google's client libraries, it succeeds and return what is expected.
function getAllTasks() {
gapi.client.tasks.tasks.list({
tasklist: 'MDIxODc1MzEwNzc4MzMxNDU2MTU6MDow'
}).then(function (response) {
console.log(response);
var arr = response.result.items;
console.log(arr);
for(var j=0;j<arr.length;j++){
console.log(arr[j].title);
}
})
}
But when I do the same using jQuery, I get 404 with the text "Login Requied" in the response body.
function getAllTasksJquery() {
$.get("https://content.googleapis.com/tasks/v1/lists/MDIxODc1MzEwNzc4MzMxNDU2MTU6MDow/tasks",function (data,status) {
console.log(data,status);
var arr = data.result.items;
console.log(arr);
for(var j=0;j<arr.length;j++) {
console.log(arr[j].title);
}
});
}
Can someone tell me what am I doing wrong ?
So after hours of search, I finally figured this out. Since I was using the Google's JS Client libraries, I almost ignored the fact that I have to pass my oauth2 access_token with each API call. Only then will the API know the account to access.
More specifically, pass the access_token in the header while making API requests. Here is a jQuery snippet for the same :
$.get(`https://www.googleapis.com/tasks/v1/users/#me/lists`,{access_token: AccessToken}, function (data,status) {
console.log(status,data);
});
Hope it helps the others...
I keep getting this error in my service worker that is stopping my page from working offline, Iv'e done a lot of testing and I think Iv'e figured out where the problem is but not why it is happening. There seems to be a problem with the fetch function, so when it tries to fetch the 'Index.html' page, it returns the error of 'uncaught promise'. I only think this because when I remove the piece of code that fetches the pages, and reupload it to git, there doesn't seem to be any errors, but I could also be wrong. Below is the code I'm using to get this to work. I haven't uploaded all of it, as it would be a lot of code to sieve through, I've only put in the code where I think the problem is, I can put the rest of the code in if anyone wants to see it though. Any help would be really appreciated as this is driving me insane! Thankyou.
var BASE_PATH = "/assignment-real-final/";
var TEMP_IMAGE_CACHE_NAME = 'temp-cache-v1';
var CACHE_NAME = 'gih-cache-v7';
var newsAPIJSON = "https://newsapi.org/v1/articles?source=bbc-news&apiKey=c5b2ba3cfb4c4717852bf328348da961";
var CACHED_URLS = [
// HTML
BASE_PATH +'index.html',
BASE_PATH +'staffs-uni.html',
BASE_PATH +'sign-up.html',
];
self.addEventListener('fetch', function(event) {
var requestURL = new URL(event.request.url);
// Handle requests for index.html
if (requestURL.pathname === BASE_PATH + 'index.html') { // WHERE I THINK THE PROBLEM IS
event.respondWith(
caches.open(CACHE_NAME).then(function(cache) {
return cache.match('index.html').then(function(cachedResponse) {
var fetchPromise = fetch('index.html').then(function(networkResponse) {
cache.put('index.html', networkResponse.clone());
return networkResponse;
});
return cachedResponse || fetchPromise;
});
})
);
} else if (requestURL.pathname === BASE_PATH + 'staffs-uni.html') { // WHERE I THINK THE PROBLEM IS
event.respondWith(
caches.open(CACHE_NAME).then(function(cache) {
return cache.match('staffs-uni.html').then(function(cachedResponse) {
var fetchPromise = fetch('staffs-uni.html').then(function(networkResponse) {
cache.put('staffs-uni.html', networkResponse.clone());
return networkResponse;
});
return cachedResponse || fetchPromise;
});
})
);
// Handle requests for Google Maps JavaScript API file
} else if (requestURL.href === googleMapsAPIJS) {
event.respondWith(
fetch(
googleMapsAPIJS+'&'+Date.now(),
{ mode: 'no-cors', cache: 'no-store' }
).catch(function() {
return caches.match('offline-map.js');
})
);
}
});
Based on your service worker, the URLs for your HTML documents seem to be /assignment-real-final/index.html, etc. Those are absolute URLs.
Inside your fetch handler, you pass relative URLs like index.html to your cache.match() and fetch() calls. Those are relative URLs, and the location of the service worker file will be used as the base when translating them to absolute URLs.
So, if your service worker file is located at /sw.js, the relative URL index.html will be translated to the absolute URL /index.html, instead of /assignment-real-final/index.html.
That's my best guess as to why there would be a cache miss and a network failure—you're using the wrong URLs.
After too many hours, I cannot for the life of me get this example working. I'm following Ben Lesh's excellent guides to mocking $http requests in Angular, but for some reason the service request is not sending.
I have verified that the service is working properly by building a separate HTML DOM and applying my app and a tiny controller to it. I'm using Jasmine 1.3 and Angular 1.2.9 (and angular-mocks.js of course).
Here's the app:
var app = angular.module('myApp', []);
app.factory('httpBasedService', function($http) {
return {
sendMessage: function(msg) {
return $http.get('something.json?msg=' + msg)
.then(function(result) {
console.log(result.data)
return result.data;
});
}
};
});
And the test:
describe("httpBasedService ", function () {
var httpBasedService,
mockBackend;
beforeEach(function (){
module('myApp');
inject(function(_$httpBackend_, _httpBasedService_) {
mockBackend = _$httpBackend_;
httpBasedService = _httpBasedService_;
});
});
afterEach(function() {
mockBackend.verifyNoOutstandingExpectation();
mockBackend.verifyNoOutstandingRequest();
});
it('should send the msg and return the response.', function () {
var returnData = {excited: true};
mockBackend.expectGET('something.json?msg=wee').respond(returnData);
var returnedPromise = httpBasedService.sendMessage('wee');
var result;
returnedPromise.then(function(response) {
result = response;
});
mockBackend.flush();
expect(result).toEqual(returnData);
});
});
I'm getting a Error: No pending request to flush ! and of course a Error: Unsatisfied requests: GET (since nothing has been sent). I watch the network requests and sure enough, no request is sent, even if I remove the mock backend.
I've commented out stuff, restructured stuff, tried lots of other examples, but to no avail. Can someone help me?
As usual, when I talk to the duck, the problem is fixed.
Turns out I was using angular-mocks.js from v1.1.0. My angular.js version was 1.2.9.
Facepalm.
Check your versions, future readers, and save yourself a few hours.
I need to send multiple get requests(required) one by one. When the count is 2-3, it works fine, but with almost 6 HTTP Get requests, sometimes some of them fails and give Internal Sever Error(500). Opening the error link in new tab gives required results.
So there is nothing wrong from server side.
I'm facing this problem both in : localhost and production.
How to deal with this situation from client side?
I've tried:
NodeJS + SocketIO to send data from server without asking. [with so much data if socket keeps writing till 60 sec. socket re-registers & restarts from beginning.]
Angular + NGResource. [internally uses http get. issue persists.]
Angular + Restangular Lib. [internally uses http get. issue persists.]
Please suggest how do I know what the problem is. Then only I can think of a solution.
Thnx!!
Here's a function in which you can wrap your HTTP calls. It will repeat the call until it passes. Beware! If the HTTP call fails 100% of the time (for example, malformed URL), then the function will not stop (In testing, the function was called >70,000 times. Apparently there is no recursion limit with promises). For that case, I've included a limited version of the function that stops after n attempts.
var persistentRequest = function(requestFn) {
var deferred = $q.defer();
requestFn().then(function() {
deferred.resolve();
}, function() {
persistentRequest(requestFn).then(
function() {
deferred.resolve();
}
);
});
return deferred.promise;
}
var persistentRequestLimited = function(requestFn, n) {
var deferred = $q.defer();
if (n <= 0) {
deferred.reject('Did not complete in given number of tries');
} else {
requestFn().then(function(data) {
deferred.resolve(data);
}, function() {
persistentRequestLimited(requestFn, n-1).then(
function(data) {
deferred.resolve(data);
},
function(rejection) {
deferred.reject(rejection);
}
);
});
}
return deferred.promise;
}
For example, use it like:
persistentRequest(function() {
return $http.get('/myurl');
});
persistentRequestLimited(function() {
return $http.get('/myurl');
}, 10);
Don't forget to inject $q into your controller/service/etc.