In angular JS 1.6 how to call the two functions simultaneously after we get the success response from service. Is it possible ?
Wrap both function within .success():
this.myPromise().success((response) => {
this.myFunctionOne(response);
this.myFunctionTwo(response);
})
This way, .success() will fire two functions.
But actually, I have no idea if this is what you were asking for..
Related
async function in OnInit firing after template has loaded
Apologies if this has been asked. I couldn't seem to find something speaking to my specific scenario.
In my controller, I define an $onInit function that calls a function that that in turn calls an async function. The async function has a catch block that sets a boolean for an ng-if in the template (controls whether an error message should display):
controller:
$onInit() {
initFn();
}
function initFn() {
innerFn();
}
function innerFn() {
asyncFn
.then(() => {
// does some stuff
})
.catch(() => {
boolVal = true;
})
}
template:
<div ng-if="boolVal">some-error-message</div>
I test this by sending back a Promise.reject() for asyncFn but the error message doesn't show. boolVal, however, is true. What I think is happening is that the template compiles and builds before the async call is able to finish. How do I ensure that all API calls are completed in $onInit before the template has loaded? If that isn't the problem, what am I missing?
Thanks!
I test this by sending back a Promise.reject() for asyncFn
The ES6 promises returned by Promise.reject() are not integrated with the AngularJS framework. Instead, return AngularJS promises:
function asyncFn () {
if (/* error condition */) {
return $q.reject();
};
}
AngularJS modifies the normal JavaScript flow by providing its own event processing loop. This splits the JavaScript into classical and AngularJS execution context. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.1
For more information, see
AngularJS $q Service API Reference - `$q.reject
what are common scenarios/services that I should be aware
Beware of ES6 promises -- use AngularJS promises
Beware of third-party promises -- use $q.when to convert to AngularJS promises
Beware of async/await -- they return ES6 promises
Beware of window.setTimeout - use the $timeout service
Beware of window.setInterval -- use the $interval service
Beware of jQuery.ajax -- use the $http service
Event from outside the AngularJS framework
Beware of element.addEventListener
Beware of jQuery.on
Beware of events from third-party APIs / libraries
You can also use $apply() to enter the AngularJS execution context from JavaScript.
Keep in mind that in most places (controllers, services) $apply has already been called for you by the directive which is handling the event. An explicit call to $apply is needed only when implementing custom event callbacks, or when working with third-party library callbacks.
For more information, see
AngularJS Developer Guide - Integration with the browser event loop
AngularJS $scope / $rootScope Class API Reference - $apply
I am migrating AngularJS to Angular
Trying to replace $q with Promise
I have
$q.when(btn.onClick()).finally(test => {
// code
})
I have replaced it with the below code and not sure if that is the exact replacement.
Promise.resolve(btn.onClick()).then(test => {
// code
})
From $q.when() I see we can use .resolve() for .when()
but what is the replacement for .finally()
Start by binding a component template button click to your template logic
<button (click)="onClick()">Click</button>
onClick() {}
Then you can use Promise.all for several promises, or .then for a single promise.
Although, if I may suggest, while migrating, you should consider using Observables, as they're way more powerful than promises and natively integrated with Angular.
Here is one of my previous answers to get started rapidly with Observables.
Since you mention you're migrating, using observables is preferred when possible to using promises. From the documentation:
You can often use observables instead of promises to deliver values asynchronously. Similarly, observables can take the place of event handlers. Finally, because observables deliver multiple values, you can use them where you might otherwise build and operate on arrays.
https://angular.io/guide/comparing-observables
That being said, finally is a part of the promise API and can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally
//realised that's not the question. my bad!
You could use
.then(function(){
})
as many times as you want, theres no true replacement for finally() in my knowledge
As I have studied, we can use $emit to emit the data to all the parent controllers and $broadcast to broadcast the data to all the child controllers, while we can use $on to catch the data emitted/broadcasted from $emit/$broadcast. For getting data from an external json, we use $http.get.
If we have multiple controllers nested inside each other, is it recommended to use $http.get multiple times in each controller or use $http once in the parent controller and the data is broadcasted to all the child controllers present? Or, is it better if we have a seperate service to handle all the $http.get requests that can be further used in each of the controllers?
You can make a function in the service and use it when you want like parent and child.
**Service::**
function getData() {
// Get data from API and return.
}
**Controller 1**
function getRecord() {
// call service1.getData();
}
**Controller 2**
function getRecord() {
// calll service1.getData();
}
Irrespective of which option you choose, you should call APIs ($http functions) from services. That makes them reusable.
Having said that, in your case broadcasting is not good idea. I would go with option #2.
Also if your response is going to be same for all the request from child controllers, try to save the response of first call into service and then reuse it.
I know about this question here: AngularJS : Initialize service with asynchronous data which I have used in the past on 1.1 and 1.2.
But this requires you need to use old ngRoute module. I'm using ngNewRouter (available for angular 1.x) and don't have a resolve method for the routeProvider.
However it is possible to be done in components, not with the main controller:
//before navigation finishes, useful to load required data
appController.prototype.activate = function() {
console.log ('loading data for the user');
console.log (this.authService.requestCurrentUser());
return this.authService.requestCurrentUser();
}
Still, the main controller it's not a component, so $componentLoaderProvider is not available.
How do I make the app wait for async data, without adding return this.authService.requestCurrentUser() to every component?
Thank you!
Hi I am using angularJS to my project and I use $http function to retrieve some data. but i want to hold other statements from executing until $http finishes. Any suggestions?
Use .then() and place your rest of the codes there.
Ex:
$http(//your call here)
.then(function (contents) {
alert(JSON.stringify(contents));
});