If the server goes offline, it will not produce an error message

Running a factory in AngularJS

  angular.module('app.services',[])
    .factory('myFactory', function($http){
      return {
        getData: function(){
          return {animal: 'dog'}
        },
        isUser: function() {
          var url='http://parleyvale.com/isUser/';
          var promise=$http.get(url).   
            success(function(data, status) {
              console.log(data);
              console.log(status);
              return data;
            }).
            error(function(data, status){
              console.log(data || "Request failed");
              console.log(status);
              var data = {message: "Server is down"}
              return data;
            });
          return promise;
        },    ...

Utilizing data from the factory in a controller

  angular.module('app.controllers',[])
    .controller('MainCtrl', ['$scope', 'myFactory', function($scope, myFactory){
      $scope.factoryOutput=myFactory.getData();  
      $scope.isUser=myFactory.isUser().then(function(data){
        console.log(data.data.items);
        $scope.factoryOutput2=data.data.items
      });  ...

Challenges when server is down

x GET http://parleyvale.com/isUser/ net::ERR_CONNECTION_REFUSED

Seeking solution for handling errors

Explore http://jsbin.com/nebed/2/edit

Answer №1

Your controller code is missing a crucial second function argument in the then method to handle failures:

$scope.isUser=myFactory.isUser('tim').then(function(data){
    console.log(data.data.items);
    $scope.factoryOutput2=data.data.items
}, function(data){ $scope.factoryOutput2 = data });  

Check out the updated version in your JS Bin

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

Ajax fails to provide a response

Hey there, I'm trying to save the response from an HTML page and store the content of that page. However, every time I try, I keep getting an error message. What am I doing incorrectly? <script type="text/jscript"> var page = ""; $.aj ...

Preserving the background image on an html canvas along with the drawing on the canvas

Can users save both their drawings and the background image after completing them? var canvas = document.getElementById("canvas"); // This element is from the HTML var context = canvas.getContext("2d"); // Retrieve the canvas context canvas.style.ba ...

Tips for customizing bootstrap code for registration form to validate against duplicate emails?

The contact_me form utilizes default code to handle success or failure responses from the server. The code calls msend_form.php for communication with the database and always returns true. It allows checking for pre-existing email addresses in the database ...

Should we consider using extra url query parameters as a legitimate method to avoid caching or enforce the updating of css/js files?

Is it acceptable to include extra URL query parameters in order to avoid caching or enforce the updating of CSS/JS files? /style.css?v=1 Or would it be preferable to rename the file/directory instead? /style.1.css I've heard that this could potent ...

JavaScript - The onkeypress event continuously adds text to the end

In my Angular application, I have implemented an input field with the onkeypress event handler to automatically remove any commas entered by the user: <input name="option" ng-model="main.optionToAdd" onkeypress="this.value = this.value.replace(/,/g ...

"Exploring the world of Mean.js with Node.js background functionalities

Struggling with my mean.js app as I try to figure out how to implement background processes. I want these processes to run continuously, interacting with the mongodb database and handling tasks like cleanup, email notifications, and tweets. I need access ...

The POST request from the form is returning a null value

I am currently facing an issue with using post in Express and BodyParser to insert data from a form in an EJS file into MySQL. The data keeps returning null, indicating that it is not being parsed correctly from the form to the backend. Can anyone offer as ...

What is the best way to halt a specific function in jQuery?

I recently developed a website for my photographer friend, and I implemented a feature where the home page is initially blurred. Visitors can click a button to unblur the content. While the functionality works smoothly, there's one issue - every time ...

The requested path /releases/add cannot be located

In my CRUD application, I have a feature that allows users to create releases by adding a version and description. This is achieved through a button and input fields for the details. <button (click)="addRelease(version.value, description.value)" [d ...

Secure User Verification in Laravel 5 and AngularJs sans the need for JWT Tokens

I am currently working on a project that involves utilizing a Laravel-based back-end and a front-end built with both Laravel and AngularJS. After completing 40% of the back-end development, I am now faced with the task of implementing the front-end. Howev ...

Discover the secret to instantly displaying comments after submission without refreshing the page in VueJS

Is there a way to display the comment instantly after clicking on the submit button, without having to refresh the page? Currently, the comment is saved to the database but only appears after refreshing. I'm looking for a solution or syntax that can h ...

Can HTML Elements be used within a Contenteditable section?

I am facing an issue with a contenteditable tag on my website. Users are unable to type code into the tag and have it display as an actual element instead of just text. Is there a way for users to input full, working HTML elements in a contenteditable box ...

What sets apart `Object.merge(...)` from `Object.append(...)` in MooTools?

This question may seem simple at first glance, but upon further inspection, the MooTools documentation for the 'append' and 'merge' methods appears to be identical. Here is the code snippet provided in the documentation: var firstObj ...

Struggling to find the definition of a Typescript decorator after importing it from a separate file

Consider the following scenario: decorator.ts export function logStuff(target: Object, key: string | symbol, descriptor: TypedPropertyDescriptor<any>) { return { value: function (...args: any[]) { args.push("Another argument ...

callback triggering state change

This particular member function is responsible for populating a folder_structure object with fabricated data asynchronously: fake(folders_: number, progress_callback_: (progress_: number) => void = (progress_: number) => null): Promise<boolean ...

Listen for the 'open' event on a node HTTP server

This question pertains to a previous inquiry I had about node httpServer encountering the EADDRINUSE error and moving to the next available port. Currently, my code looks like this: var port = 8000; HTTPserver .listen(port, function() { console.lo ...

Is there a way to prevent the annoying "Reload site? Changes you made may not be saved" popup from appearing during Python Selenium tests on Chrome?

While conducting automated selenium tests using Python on a Chrome browser, I have encountered an issue where a popup appears on the screen after reloading a page: https://i.stack.imgur.com/gRQKj.png Is there a way to customize the settings of the Chrome ...

Conditionality in the ng-repeat directive of AngularJS

Could someone please help with setting a condition in ng-repeat inside a custom directive call? <map-marker ng-repeat='obj in objects' title= 'obj.name' latitude= 'obj.last_point().latitude' longitude= ' ...

Tips for recognizing the click, such as determining which specific button was pressed

Currently, I am utilizing Angular 6. On the customer list page, there are three buttons - "NEW", "EDIT", and "VIEW" - all of which render to one component. As a result, it is crucial for me to determine which specific button has been clicked in order to ...

Struggling to make jQuery code function properly in Wordpress, despite attempting to use noConflict

I have created a custom image grid gallery in WordPress using HTML and CSS, complete with popups and sliders. I had to code it myself because I couldn't find a suitable plugin that matched my design preferences. I have tested the functionality on my ...