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

how to use angular js with springs
Yes, You can integrate AngularJs with Spring and JSP. It is good solution for now days web application Archistructure.
Don
0 0
7
I completed my graduation in 2017, now working as an HR Executive in a Consultancy. I want to move to IT Sector. Which course is best for me to learn and get success in life? Please Suggest me
Dear Kumar, My suggestion is to - become good in one programming language - preferably Java and one O/S preferably Linux. Be aware of Open Source systems. Try to identify the opportunities in your existing...
Kumar

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
Where should we implement the DOM Manipulation in Angularjs ?
Basically in angular js dom manipulation is perform in controllers. But in angular 2 we should implement the DOM manipulation using structural directives. Structural directives are used to remove and add...
S.V.R
0 0
6
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

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

Ask a Question

Related Lessons

Introduction to Angular JS
What is AngularJS? AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly...

Angular 4/5 Course
Angular 4/5 Syllabus: HTML Fundamentals: HTML Introduction How WebWorks? What is a Web Page? HTML Basic HTML Fundamentals HTML Attributes HTML Styles HTML Controls HTML Formatting HTML...


Happiness Or Satisfaction: How To Quit Your Day Job?
Four years ago on a sunny April morning, I slinked into my new office building, suit slightly too big, 24-years-old and clueless. It was my first day working at a large, prestigious Organization. The...

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....

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