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

Hello all, I am working as a web (graphic) designer right now, I know basics of HTML, CSS, Photoshop illustrator but I want to become a developer. So I want to know that is Angularjs developer is a good career?

AngularJS is a structural framework for dynamic web apps. It address many of the challenges encountered in developing single-page applications so It has a very good career prospects.
Himani
Hi, I am working as a web designer and want to work as UI developer. So what should I have to learn initially? And learning Angular Js would be a good option?
It is good choice web designer to become web developer (UI developer). Start with the basics first learn HTML and CSS, Then go and continue with bootstrap and Angular js.
Mudita
job opportunities after doing an hands on training for angular.js at kolkata
AngularJS is high in demand if You have good hands on it.
Subhadeep
Hi, I am pursuing MBA 1st Year. I want to learn Digital Marketing. Is it right for career growth, or should I choose to learn some other technologies? If yes, please give me your suggestions that help me to get a JOB in the IT Sector.
Hi Sai, To find right career path you need to try things ( Which is long way). I would suggest you to learn multiple things ( implementation is important part) and then find your intrest and dive in to...
Sai

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

Dependency Injection in Angular 2
Dependency injection Dependency injection is a way to supply a new instance of a class with the fully-formed dependencies it requires. Most dependencies are services. Angular uses dependency injection...

Why AngularJS Got Popular
AngularJS became very popular due to its easy two-way data binding, MVC architecture, built-in module system, dependency injection, and routing package. Initially built as a hobby project by Misko Hevery...

AngularJS Basics- 1
This is my first blog.I am just explaining the basics of AngularJS and Sample application in an interesting way so that anyone can create an Angular application. Let’s see how we can create :) Angular.js...

Learning a new technology
Each and every day new technologies are getting introduced. Its quite clear that to be part of the fast moving professional world you should be upto date with the cutting edge technologies in the market....
S

Saurav Singh

1 0
0

Difference Between JavaScript and AngularJs
JavaScript: JavaScript is a programming language written for websites to run in the browser. It is used to validate the user input at browser level itself before submitting the page to server for...
S

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