Angular 4 Promises, and Route Protection
Promises are a core feature of AngularJS – whether you understand them or not, if you use AngularJS you’ve almost certainly been using them for a while.
A promise represents the eventual result of an operation. You can use a promise to specify what to do when an operation eventually succeeds or fails.
So let’s see this in action. Look at the code below:
$http.get(“/api/my/name”);
This code uses the $http service to perform an HTTP GET on the url ‘/api/my/name’. Let’s say that this is an api we’ve implemented on our server that returns the name of the logged in user.
Now a common mistake for JavaScript newcomers might be to assume that the function returns the name:
// The WRONG way!
var name = $http.get(“/api/my/name”);
It doesn’t – and in fact it can’t. An HTTP request has to be executed, it’ll take a while before it returns – it might not return at all if there are errors. Remember, when we make requests in JavaScript we’re using ajax which is asynchronous javascript and xml. The key word here is asynchronous – we return control to the browser, let it make a request and give it a function to call when the request completes.
So let’s see how you actually make the request.
var promise = $http.get(“/api/my/name”);
promise.success(function(name) {
console.log(“Your name is: ” + name);
});
promise.error(function(response, status) {
console.log(“The request failed with response ” + response + ” and status code ” + status);
});
Now we use the promise object to specify what to do when the request succeeds, or when it fails. Remember, the functions we pass to success or error will be called later – when this block is finished executing we don’t have the name, we’ve just specified what to do when we do eventually get it – or what to do if we fail to get it.
As a convenience, the success and error functions actually just return the promise, so we can simplify the code:
$http.get(“/api/my/name”)
.success(function(name) {
console.log(“Your name is: ” + name);
})
.error(function(response, status) {
console.log(“The request failed with response ” + response + ” and status code ” + status);
});
In fact, success and error are special functions added to a promise by $http – normally with promises we just use then, which takes the success function as the first parameter and the error function as the second:
$http.get(“/api/my/name”)
.then(
/* success */
function(response) {
console.log(“Your name is: ” + response.data);
},
/* failure */
function(error) {
console.log(“The request failed: ” + error);
});
We’ll see more about the difference between success, error and then later.
That’s all there is to it – a promise lets us specify what to do as the result of an operation.
IT Professionals, Web Developers, web programmers, IT students can use the below links to be updated on Angular 4