"Incorporating error messages into the Angular callback API for when it fails

Currently engaged in developing an Angular application that interacts with the flickr API. To effectively use the response from flickr, it is necessary to define a jsonFlickrFeed callback function. Check out this link for detailed instructions.

The functionality of my angular app is flawless; I receive the response and display the data on the screen without any issues.

However, I want to enhance the user experience by displaying an error message if the data fails to load. Unfortunately, I am struggling to implement this feature as the usual method I had in mind always triggers an error due to the nature of the API. Here's what I have attempted:

app.controller('testCtrl', function (getFlickrData) {
   var testCtrl = this;
   this.loading = true;
   this.error = false;

   //Retrieve data from Flickr
   getFlickrData.getData().catch(function (err) {
       //Display error
       console.log(err)
       testCtrl.error = true;
   })
   .finally(function () {
     // Hide loading spinner regardless of success or failure.
     testCtrl.loading = false;
   });

   //Callback function required by the API
   jsonFlickrFeed = function(data){
     console.log(data);
   } 
});

Below is the factory I utilize to make the GET request to Flickr:

app.factory('getFlickrData', function($http){
    return{
        getData: function(){
            return $http.jsonp('https://api.flickr.com/services/feeds/photos_public.gne?tagmode=all&format=json');
        }
    }
});

The error logged in the console appears as follows:

{data: undefined, status: 404, config: Object, statusText: "error"}

Finally, here is the html section that consistently displays, even when content loads successfully:

<div ng-show="testCtrl.error" class="error">
   <p>Apologies, but there was an issue loading the content. Please try again later.</p>
</div>

In essence, my question boils down to how to assess the success/failure of a callback (potentially).

You can view a relevant jsfiddle here to better understand the problem I am attempting to resolve.

Answer №1

Never fear, this solution is here for you :)

As per the AngularJS API documentation on $http, it seems that there is no "finally" method available—only "success" and "error" can be utilized in this context.

app.controller('testCtrl', function (getFlickrData) {
   var testCtrl = this;
   this.loading = true;
   this.error = false;

   getFlickrData.getData().success(function (data) {
       console.log(data);
       testCtrl.loading = false;
   })
   .error(function () {
     testCtrl.loading = false;
     testCtrl.error = true;
   });

})
.factory('getFlickrData', function($http){
    return{
        data:{},
        getData: function(){
            var self = this;
            return $http.jsonp("https://api.flickr.com/services/feeds/photos_public.gne?tagmode=all&format=json&jsoncallback=JSON_CALLBACK");
        }
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Assign a unique attribute to a DOM element in React version 15.5.4

Within the render method, I currently have the following structure: <h1 customAttibute="customValue" className="classValue">This h1</h1> However, when rendered in the browser, it appears like this: <h1 class="classValue">This h1</h1 ...

Using the Rails form_for with file_field and remote => true along with format => :js

I have a form_for with a file_field included. Upon submission, the controller responds with a .js file to be executed. The presence of the file_field is optional. When I upload a file, the .js file opens as plain text and does not execute. If no file is ...

Having trouble storing information in a leveldb file with a batch operation

I recently delved into learning level.db with the level module in node.js var level = require('level') var db = level('batch.db', { valueEncoding: 'json' }) var batch = [] for (var i = 0; i < 10; i++) { batch.push({ key ...

Seeking guidance on mapping out a Rails application website: Retrieve JSON data from another website and transmit it for use in JavaScript Ajax calls

I am an aspiring web app developer who recently created my first app at the following link: Currently, I am retrieving badges (icons) from another website using jQuery.ajax(). For features like mash-ups, searching/sorting, and user login, I plan to store ...

Having trouble getting the npm package with @emotion/react and vite to function properly

Encountering an issue with the npm package dependencies after publishing, specifically with @emotion/react. This problem arose while using vite for packaging. Upon installing the package in another project, the css property appears as css="[object Ob ...

What steps should be taken to gain access to the FormController if the form is contained within a directive?

Here is the code for my custom directive: restrict: 'E', scope: { }, templateUrl: 'directives/my.directive.html', link: function(scope) { // I want to be able to access "myForm" here (e.g., to setPristine(), etc.) scope.custom ...

Adding a newline character ( ) to each element in the array before converting

Why, when I use JSON.stringify, is appending to the value? Take a look at this example link: http://jsfiddle.net/7nketLmy/ var formData = new Array(); if ($(this).get(0).tagName.toUpperCase() === 'DIV' ){ content = $(this).html(); ...

What is the best way to stylize a date using Bootstrap-datepicker?

While this topic is well-known, I have a slightly more complex question regarding it. I have gone through the documentation here. My goal is to display the date in French format (dd/mm/yyyy) and save the value in US format (yyyy-mm-dd). Additionally, I nee ...

What is the best way to store an image file using html/angularjs?

I'm facing a challenge in my app where I need to save an image on one page and then retrieve it on another. So far, I have explored three different methods but none of them seem to be working for me: First, I attempted to use 'Parse.File' w ...

Toggle Checkbox Group for Both Multiple and Single Selection Options

Need help with a function to enable only one checkbox for single selection or multiple checkboxes for multiple selection. Use MultipleCheckbox(0) for single selection or MultipleCheckbox(1) for multiple selection. function MultipleCheckbox(elem){ i ...

Identify modifications to properties in Angular

What is the most effective method for responding to property changes within a component? I am seeking a solution that will trigger a specific function every time a property in a component is altered. Consider the following example with a single component: ...

If someone rapidly clicks on an AngularJS app, the page fails to load

Just a heads up - I am pretty new to Angular. Most of the code is from a tutorial on Lynda that I'm experimenting with. I've noticed an issue when I try to implement a type of "pagination" feature to display various elements from a data.json file ...

I am wondering why it is necessary to utilize the substr PHP function in order to escape the colon in the Slim index.php

I have encountered an issue with my slim route (index.php) where it only returns data to Angular (app.js) when I escape the parameter colon (:id) using the PHP function substr($id,1). If I comment out the substr function, the return is false due to the pr ...

The RGB values of a dynamically loaded image being drawn to a canvas in JavaScript are slightly off

After hosting some .PNG images on my NGINX webserver, I noticed a discrepancy in the RGB values when loading and drawing them on a canvas using context.drawImage(img, 0, 0); and retrieving the image data using context.getImageData(x, y, 1, 1).data. Interes ...

The animation using Jquery and CSS is experiencing some glitches on Safari when viewed on an

Why is smooth animation not working on iPad Safari with jQuery animate? $('#myId').css({ 'left': '-100%' }).animate({ 'left': '0' }, 300, 'linear'); I also tried using the addClass option and in ...

Step-by-step guide to accessing a PDF file stored locally using Angular2 and HTML5

I am attempting to access a .pdf file in local storage using an iFrame. Here is the code I have tried: In HTML file <object [data]="sanitizer.bypassSecurityTrustResourceUrl(selectedItem.FilePath)" type="application/pdf"> <iframe [src]="sanitizer ...

Using gulp to duplicate files from a specific directory nestled within a larger folder structure

I'm trying to figure out how to address this issue: My goal is to transfer all fonts from bower_components to .tmp/assets/fonts. However, the complication arises with some fonts being .svg files. If I were to use the following code in a typical manne ...

Implementing a transition effect to the drawimage function

I am currently working on implementing a transition effect for an image inside a canvas element. I have provided a snippet below to demonstrate my progress so far. Can anyone guide me on how to incorporate a transition animation for the image within the c ...

Another approach to utilizing ajax with JSON data

Currently, I am working on creating a web solution for a company and am facing an issue with retrieving PHP variables for my pages using AJAX. Unfortunately, the server of this company is quite outdated, which means that I am unable to utilize JSON by us ...

How to break down JSON into individual elements using JavaScript

{ "name": "Sophia", "age": "Unknown", "heroes": ["Batman", "Superman", "Wonder Woman"], "sidekicks": [ { "name": "Robin" }, { "name": "Flash Gordon" }, { "name": "Bucky Barnes" } ...