UrbanPro

Learn Angular.JS from the Best Tutors

  • Affordable fees
  • 1-1 or Group class
  • Flexible Timings
  • Verified Tutors

Search in

How would you make an Angular service return a promise please explain this one with a example?

Asked by Last Modified  

Follow 0
Answer

Please enter your answer

Java Trainer

.then() method do the business for handling the response in synchronous manner as Java Script is asynchronous. It is useful when you want perform some logic on response object, so that it will hold the control of execution.
Comments

Get trained with IT experts in .NET MVC, Android and Xamarin.

Promises are used to write asynchronous code. And many libraries and api's return promises for asynchronous operations. Promises are used to call api's from remote server. When our browser work asynchronously then it will call a service and go to next function, and when our result will ready it will...
read more
Promises are used to write asynchronous code. And many libraries and api's return promises for asynchronous operations. Promises are used to call api's from remote server. When our browser work asynchronously then it will call a service and go to next function, and when our result will ready it will provide a service using promise. This will be explained using following example. A manager ask to his employee to do some report. And employee will take few time for it. Then in between this time manager has some work. Manager does not know the result of report which will employee come with. Weather it is good or bad or doesn't get the report. After some time employee will come with report . In this example manager is component and employee is service which make promise to manager to get back with report. This is a asynchronous call of API service. read less
Comments

A teacher who can transform your career.

Working With Promises in AngularJS Services. Let's talk about working with promises in AngularJS. To start, $q is a great implementation of promises, allowing you work with deferred objects and be more efficient with Ajax calls. $q api has few useful methods, first one is to create new deferred object...
read more
Working With Promises in AngularJS Services. Let's talk about working with promises in AngularJS. To start, $q is a great implementation of promises, allowing you work with deferred objects and be more efficient with Ajax calls. $q api has few useful methods, first one is to create new deferred object using $q.defer(), so this object could be resolve in the future using $.q.defer().resolve and also to be reject using $.defer().reject methods. Explore Angular Courses When executing Ajax calls from AngularJS services, usually we use $http which return by default a promise object which we can attach â??thenâ?? method to for result notification. But when the service should fetch data from the backend and allow more than one AngularJS controllers to use, it doesnâ??t make the make the most sense to fetch everything from the server every time. Then, we should save the data in local variable inside the service. So when the AngularJS controller calls the service api to get the data, it could be a promise from the Ajax call or the data stored from previous call. The AngularJS controller should be able to differentiate between the cases, so thats not an ideal practice. The way of doing it is to wrap the data stored in AngularJS service with another $q api called $q.when which can treated as a promise for both cases, so when the $q.when receive a promise it will be resolved when the promise will and if it receive a real data it will be resolved immediately. That is transparent to the controller and this is a good practice. Hereâ??s a full code snippet below based on the above overview. (function() { 'use strict'; angular .module('testApp') .service('testService', testService) .controller('testCtrl', testCtrl) .controller('testCtrl2', testCtrl2); function testService($http, $q) { // will hold backend posts var posts = undefined; // fetch all posts in deferred technique this.getPosts = function() { // if posts object is not defined then start the new process for fetch it if (!posts) { // create deferred object using $q var deferred = $q.defer(); // get posts form backend $http.get('http://jsonplaceholder.typicode.com/posts') .then(function(result) { // save fetched posts to the local variable posts = result.data; // resolve the deferred deferred.resolve(posts); }, function(error) { posts = error; deferred.reject(error); }); // set the posts object to be a promise until result comeback posts = deferred.promise; } // in any way wrap the posts object with $q.when which means: // local posts object could be: // a promise // a real posts data // both cases will be handled as promise because $q.when on real data will resolve it immediately return $q.when(posts); }; } function testCtrl($scope, testService) { $scope.getPosts = function() { testService.getPosts() .then(function(posts) { console.log(posts); }); }; $scope.getPosts(); } function testCtrl2($scope, testService) { $scope.getPosts = function() { testService.getPosts() .then(function(posts) { console.log(posts); }); }; $scope.getPosts(); } })(); credit: appendto.com read less
Comments

Web Application Development

using$q you can return a promise. for ex. if you have a function called updateProduct in the ProductService you can do as below var _updateProduct = function (product) { var deferred = $q.defer(); $http.defaults.useXDomain = true; $http({ url: baseUrl + 'api/product/', ...
read more
using$q you can return a promise. for ex. if you have a function called updateProduct in the ProductService you can do as below var _updateProduct = function (product) { var deferred = $q.defer(); $http.defaults.useXDomain = true; $http({ url: baseUrl + 'api/product/', method: "POST", data: product//, headers: { 'Content-Type': 'application/json; charset=utf-8' } }).success(function (modifiedProduct) { deferred.resolve(result.data); }).error(function (error) { deferred.reject(); }); return deferred.promise; }; read less
Comments

View 2 more Answers

Related Questions

I want to join tutorial for angularjs with asp.net mvc. Please provide the details location of class, fee, duration etc...
Hi Asif, i will provide the angular js completed course training with one project and this project are combination of angular js and mvc web api . contact me if you are interested
Asif
What are the technologies that every Full Stack JavaScript developer should know?
Full Stack consists of 3 categories. 1. Front End Technologies like HTML5, CSS 3, JavaScript (Angular JS / React JS / jQuery / Vue / Plain Java Script) etc.. 2. Middleware Technologies like Node JS, Java...
Nandhini
0 0
7
How Nodejs and Angular Work together?
Angular just a client side presentation layer , create factories to invoke NodeJS to get the data from DB and bind it using anularjs
Raminder
How to create sliding tabs in ionic ?
We can create sliding tabs using ion-tab in ionic.
Gowravaram
0 0
5

Angular or React which is easy to learn and value in the market & job openings

Both are demanding in the market, but as per Google trends React much in demand than Angular. React is javascript based and Angular is typescript based. If you are good at javascript, then React is easy...
Ganesh

Now ask question in any of the 1000+ Categories, and get Answers from Tutors and Trainers on UrbanPro.com

Ask a Question

Related Lessons

Angular Routing Overview
a. Routes: The browser is a familiar model of application navigation: Enter a URL in the address bar and the browser navigates to a corresponding page. Click links on the page and the browser...

.NET With AngularJS Training Program Syllabus
What You will Learn in .NET with AngularJS Training Program? Introduction to .Net: Features of .Net, CTS, CLS, CLR and MSIL. C# & .Net Basics and Branching & Flow Control. OOPs Concepts,...

AngularJS Routes
Q. How to set up Angular JS Routes? Ans: Set up the application in below format: AngularJS(Folder)/ ---index.html ---home.html ---about.html ---css/style.css ---js/angular.js ---js/angular--routes.js ---js/app.js i....

Mark And Sweep Algorithm in Javascript Memory Management
This algorithm reduces the definition of "an object is not needed anymore" to "an object is unreachable". This algorithm assumes the knowledge of a set of objects called roots (In JavaScript, the root...

Be prepared to get trained--init
Before starting the training,students must be mentally prepared for acceptance of new knowledge. Students must attend training with open minded forgetting the position they are working.This will help...
S

Smartnub Softsolutions

0 0
0

Recommended Articles

Hadoop is a framework which has been developed for organizing and analysing big chunks of data for a business. Suppose you have a file larger than your system’s storage capacity and you can’t store it. Hadoop helps in storing bigger files than what could be stored on one particular server. You can therefore store very,...

Read full article >

Whether it was the Internet Era of 90s or the Big Data Era of today, Information Technology (IT) has given birth to several lucrative career options for many. Though there will not be a “significant" increase in demand for IT professionals in 2014 as compared to 2013, a “steady” demand for IT professionals is rest assured...

Read full article >

Business Process outsourcing (BPO) services can be considered as a kind of outsourcing which involves subletting of specific functions associated with any business to a third party service provider. BPO is usually administered as a cost-saving procedure for functions which an organization needs but does not rely upon to...

Read full article >

Information technology consultancy or Information technology consulting is a specialized field in which one can set their focus on providing advisory services to business firms on finding ways to use innovations in information technology to further their business and meet the objectives of the business. Not only does...

Read full article >

Looking for Angular.JS Training?

Learn from the Best Tutors on UrbanPro

Are you a Tutor or Training Institute?

Join UrbanPro Today to find students near you
X

Looking for Angular.JS Classes?

The best tutors for Angular.JS Classes are on UrbanPro

  • Select the best Tutor
  • Book & Attend a Free Demo
  • Pay and start Learning

Learn Angular.JS with the Best Tutors

The best Tutors for Angular.JS Classes are on UrbanPro

This website uses cookies

We use cookies to improve user experience. Choose what cookies you allow us to use. You can read more about our Cookie Policy in our Privacy Policy

Accept All
Decline All

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 55 lakh students rely on UrbanPro.com, to fulfill their learning requirements across 1,000+ categories. Using UrbanPro.com, parents, and students can compare multiple Tutors and Institutes and choose the one that best suits their requirements. More than 7.5 lakh verified Tutors and Institutes are helping millions of students every day and growing their tutoring business on UrbanPro.com. Whether you are looking for a tutor to learn mathematics, a German language trainer to brush up your German language skills or an institute to upgrade your IT skills, we have got the best selection of Tutors and Training Institutes for you. Read more