Sunday, July 16, 2017

AngularJS Basic Routings

Creating angular js basic routes using UI router.
AngularJS Routes empower us to actualize multiview SPA's [Single Page Applications]. A multiview application would comprise of numerous views[HTML Templates where every format is related with a particular route] which would be stacked progressively because of client activity (clicking a connection, writing a particular URL in program e.g.). Utilizing directing, AngularJS application can indicate distinctive substance in light of which course is chosen. Courses are essentially bookmark-capable URL's to particular substance [specific view] of AngularJS application.


AngularJS Routing influences hashbang URLs, implies courses are included after # in URL. For instance, regularly URL looks like http://www.angularapp.com/first/page. In a Single-Page Application, nonetheless, it would generally look like http://www.angularapp.com/#/first/page. This is because of the way that Browser treats URL with # uniquely in contrast to standard URL.

Subsequently following URL will all make same demand to server.
http://ohsome.site/#/first
http://ohsome.site/#/second
http://ohsome.site/#/third

At the point when user taps on any of these links (or specifically sorts them in the program) , same demand (http://ohsome.site/) is sent to the server. Any URL part after the # sign gets overlooked by the program in the server call. It turns into the employment of customer to manage some portion of URL after the #. AngularJS for this situation will take a gander at the course [part of URL after the #] and choose which HTML format to stack.


How about we see a brisk and basic illustration demonstrating AngularJS steering, before jumping into points of interest.



     
         AngularJS Basic Routings
     
     
      
         

AngularJS Routing Application




We should burrow further, clarifying each progression in detail.



 
 
 



1.Including the AngularJS Route Module source code in Application’s HTML
angular.module('routingDemoApp',['ngRoute']) 


First step is to incorporate the Javascript containing source code of directing module. It can be incorporated into head or body area.

2.Incorporate the ngRoute module as a reliance of our principle AngularJS application module



Following stage is to incorporate the "ngRoute" module as a reliance to the principle module. It is required before we can utilize anything from this steering module in our code.

3.Using ngView directive (Take Note: There is UI Router from the latest version! Must try it!)
 module.config(['$routeProvider', function($routeProvider){
     $routeProvider
         .when('/',{template:'This is the default Route'})
         .when('/computers',{template:'This is the computers Route'})
         .when('/printers',{template:'This is the printers Route'})
         .otherwise({redirectTo:'/'});
 }]);


Subsequent stage is to check which segment of the page AngularJS should change when the course changes. With the ngRoute module, this is finished utilizing the ng-see order in the HTML. It would be ideal if you take note of that with ngRoute, there can be just a single ng-see per application. In the event that your application requests more, you ought to favor ui-switch over ngRoute.

4.Configure $routeProvider

Characterize our courses in the config area utilizing the $routeProvider benefit. The following is the least complex arrangement to design courses utilizing @routeProvider


 $routeProvider.when(url, {
     template: string,
     templateUrl: string,
     controller: string, function or array,
     controllerAs: string,
     redirectTo: string, function,
     resolve: object
 });


AngularJS module's config work is utilized to arrange the courses. config work takes a cluster as parameter where the last component is the definition work while the others are conditions to be infused which will in the end be utilized as a part of definition work. For this situation, $routeProvide reliance is infused.

The $routeProvider gives us when(path,object) and otherwise(object) works keeping in mind the end goal to characterize all courses in one place. The when work takes two contentions:
  • In the first place contention is a URL or a URL regex that determines when this specific course is appropriate.
  • The second is a course setup protest that indicates what necessities to happen when the specific course is experienced.

In our case, we kept it straightforward by advising AngularJS to stack just a specific HTML format that we indicate inline, when that course is experienced. Design protest gives numerous setup choices to arrange. We will go in points of interest in the following segment.

The generally work is a catch-all capacity which indicates what AngularJS needs to do if the client tries to go to a URL that is not determined in the design. It takes design question as the contention. More often than not, notwithstanding, you will see that generally work takes redirectTo as a key which will basically divert any obscure URL to the course specified in estimation of redirectTo key.




In Detailed Route Configuration Object 

Past case was exceptionally basic where we basically stacked distinctive layouts for various courses, and that's it. The AngularJS course definition enables us to characterize more intricate formats. The $routeProvider.when work takes a URL or URL general articulation as the principal contention, and the course arrangement protest as the second.

The syntax with route configuration object is as follows:

 $routeProvider.when(url, {
     template: string,
     templateUrl: string,
     controller: string, function or array,
     controllerAs: string,
     redirectTo: string, function,
     resolve: object
 });


Each key is explained below:

template: At the point when the HTML to be shown is not substantial, we can inline it as a string, utilizing "layout" as a key and this string as an incentive in arrangement question. AngularJS straightforwardly embeds this format HTML into the ng-view order.


templateUrl: At the point when the HTML to be shown is perplexing and extensive, it's ideal to break them into partitioned formats/documents, and give the URL to the HTML record as the templateUrl. AngularJS loads the HTML document from the server when it needs to show the specific course.

 $routeProvider.when('/computers', {
     templateUrl: 'views/computers.html',
 });

This brings views/computers.html from the server and burdens it into the ng-view.

controller: Utilizing controller key, we can characterize the controller to be utilized for a specific course. There are two ways we can characterize the controller to be utilized for a specific course.

On the off chance that the controller has just been characterized utilizing module.controller() work in the application, we can simply indicate the name of controller, and that controller code would be open from inside course layout.


 //earlier in application
 App app = angular.module('myApp',['ngRoute'])
 app.controller('AppController1', [function() {
          var self = this;
          self.message= 'Hello';
          self.doSomething = function() {
              self.message = 'Bye';
          };
      }]);
  
  
 app.config(['$routeProvider', function($routeProvider){
            $routeProvider
                .when('/',{template:'This is the default Route'})
                .when('/computers',{template:'This is the computers Route. And the message is {{ctrl.message}}', 
                                                controller:'AppController1 as ctrl'})
                .when('/printers',{template:'This is the printers Route'})
                .otherwise({redirectTo:'/'});
    }]);


Other case is to characterize the controller inline, ideal alongside route


 $routeProvider.when('/computers', {
    template: 'This is the computers Route',
    controller: ['$log', function($log) {
           $log.log('Computers route has been loaded!');
    }]
 });

Above case, we have characterized the controller definition inline with the route that we needed to, without copying the code.


redirectTo: There may be situations where you need to divert to an alternate URL [For case, some URL has been moved,or does not exist anymore]. In those cases, "redirectTo" key comes helpful. It is exceptionally valuable in blunder taking care of.


 $routeProvider.when('/computers', {
     template: 'This is the computers Route.'
 });
 $routeProvider.when('/desktops', {
     redirectTo: '/computers'
 });


In above case, AngularJS will open/#/PCs when client enters either/#/PCs or/#/desktops in the program.


resolve: Resolves gives us an approach to characterize an arrangement of asynchronous assignments to execute before the route is stacked. In the event that any of the offbeat assignments is not fruitful, route won't be stacked. It is a helpful approach to check for instance if a client is signed in and has approval before getting to a secured route. A resolve is an arrangement of keys and functions. Each function can restore an esteem or a guarantee.


Let’s see this using a more realistic setup:

$routeProvider
.when('/items/computers', {
    templateUrl: 'items/computers',
    controller : "ItemListController as itemListCtrl",
    resolve: {
          async: ['ItemService', function(ItemService) {
               return ItemService.fetchAllItems('computers');
                          }]
                }
})

App.factory('ItemService', ['$http', '$q', function($http, $q){
return {
 
    fetchAllItems: function(category) {
            return $http.get('http://localhost:8080/Spring4MVCAngularJSRoutingExample/item/'+category)
                    .then(
                            function(response){
                                return response.data;
                            }, 
                            function(errResponse){
                                console.error('Error while fetching Items');
                                return $q.reject(errResponse);
                            }
                    );
    }
};

}]);

App.controller('ItemListController', ['async', function(async) {
  var self = this;
  self.items=async;
}]);


In above illustration, when client tries to get to/thing/PCs, settle comes in real life. It has an arrangement of key [it has named "async" here however you can name anything you want] and function. There can be more than one key:function in one settle definition. function in this case takes a client characterized benefit "ItemService" as a reliance and calls fetchAllItems function which send a demand to server. In this specific situation, resolve restores a guarantee, which is passed in controller here. In the event that the server returns unsuccessful reaction, route won't be stacked. On the off chance that the server reaction in progress [list of items], route gets stacked.


Access route params using $routeParams service

Routes can have parameters. These parameters would then be able to straightforwardly be gotten to in controllers utilizing AngularJS #routeParams benefit. We should take an illustration:


     
         AngularJS Basic Routings
     
     
       
         

AngularJS Routing Application



.

That's it! In this tutotial, we just successfully created the basics of Page Routing using AngularJS




No comments:

Post a Comment

PHP IMAP - Get Emails from GMAIL

Fetching emails from your GMIAL account is easier than what you expected. With the use of PHP IMAP Extension, you can easily fetch your e...