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

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
How do we save Data in Angular?
First you need save the data in local storage and after this you need have a json to store data.
Raminder
How to create sliding tabs in ionic ?
We can create sliding tabs using ion-tab in ionic.
Gowravaram
0 0
5

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

Ask a Question

Related Lessons

Pro Developer Program Syllabus
What you will learn in Pro-Developer Program: i. Introduction to Web Technologies. ii. Introduction to .Net - Features of .Net, CTS, CLS, CLR and MSIL. iii. C# & .Net Basics - Data Types,...

Remote Learning Do's and Dont's
In the Present fast-paced world, people are facing challenges concerning keeping themselves always with the up to date technologies or industry changes. When it comes to the IT industry, it is becoming...
V

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

Introduction to Programming Languages
What is a Programming Language? A programming language is a formal computer language or constructed language designed to communicate instructions to a machine, particularly a computer. Programming languages...

$scope in AngularJS
Scope is an object that refers to the application model. It is an execution context for expressions. Scopes are arranged in hierarchical structure which mimic the DOM structure of the application. Scopes...

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