ANGULAR2 Learning Notes--Detailed router model (Router) _angularjs

Source: Internet
Author: User
Tags export class angular2 router

Angular2 a modular view of Web applications, a Web application developed using ANGULAR2, is a component tree. Components are broadly divided into two categories: a generic component such as list, table, and universal, a business component designed for business development. Most of the time in actual development we need to deal with business components. For spa applications, a common problem is how to control the page switching, the common way to solve this problem is to use the router to achieve.

Routing configuration

Now let's take a look at the generic router model by putting aside Angular2. Generally speaking, spa applications require routing configuration information:

[
 {path: ', Pathmatch: ' Full ', Redirectto: '/inbox '},
 {
  path: ': Folder ',
  children: [
   {
    path: ',
    component:conversationscmp
   },
   {
    path: ': Id ',
    component:conversationcmp,
    Children: [
     {path: ' Messages ', component:messagescmp},
     {path: ' Messages/:id ', component:messagecmp}
    }
  ]
 },
 {
  path: ' Compose ',
  component:composecmp,
  outlet: ' Popup '
 },
 {
  path: ' Message/:id ',
  component:popupmessagecmp,
  outlet: ' Popup '
 }
]

This configuration information defines the potential routing status (Router state) of the application. A routing state represents a component placement information. Now let's look at this configuration from a different perspective:

In this configuration tree, each node is a route, and it corresponds to a component.

Routing Status

In the view of the routing tree, each routing state is a Shang tree of the configuration tree. Under the routing state in the following figure, the component that is ultimately activated is conversationcmp:

Navigation

The primary task of a router is to control navigation between different routing states and to update the component tree. As the following illustration shows, the routing status changes when we navigate to another page, and the components that appear on the page follow the changes.

So far, the basic model of the router has been introduced, so let's take a look at the routing model in ANGULAR2.

ANGULAR2 Routing processing process

ANGULAR2 the process of treating a URL is:

1. Apply redirection

2. Identify Routing Status

3. Application of Sentinel and data transmission

4. Activate the corresponding component

redirect

Let's say we're visiting the address: HTTP://HOSTNAME/INBOX/33/MESSAGE/44. The router first depends on the configuration rule:

{path: ', Pathmatch: ' Full ', Redirectto: '/inbox '}

To determine if the redirection is required, if our URL is http://hostname/at this point, or redirect to Http://hostname/inbox, according to the Configuration rule: folder, the component that is activated at this time is conversationcomp. But now our URL is http://hostname/inbox/33/message/44, so no redirection will occur.

Identify routing status

The router then distributes a routing status for this URL. According to the configuration rules

{
  path: ': Folder ',
  children: [
   {
    path: ',
    component:conversationscmp
   },
   {
    path: ' : Id ',
    component:conversationcmp,
    children: [
     {path: ' Messages ', component:messagescmp},
     {path : ' Messages/:id ', component:messagecmp}
    ]
   }
 

/INBOX/33/MESSAGE/44 First match: folder, the corresponding component is conversationcmp, then into the sub configuration, ' Message/:id ', messagecmp component is activated.

According to the state tree of the above graph, we can see the routing state corresponding to the messagecmp and conversationcmp. At the same time, an object called Activation route (Activatedroute) will be created and accessed in messagecmp, through Activatedroute we can get its routerstate properties, By routing state We can get specific parameters such as ID corresponding to 44. From then on, you can see that the parent parameter ID (33) must access the routing state of the parent.

  Ngoninit () {
    this.sub = this.router.routerState.parent (This.route). Params.subscribe (params => {
      This.parentrouteid = +params["id"];
  }

Sentinel and distributing data

The Sentinel's role is to determine whether the application is allowed to switch between different states, for example: if the user does not log in, it is not allowed to enter the message page. The Sentinel can be used to determine whether to allow access to this routing state and whether to leave this routing state. The canactivate in the following example is used to determine whether access is allowed, and the service class needs to inherit the Canactivate interface.

 Import {Authguard} from        ' ... /auth-guard.service ';

Const Adminroutes:routes = [
 {
  path: ' admin ',
  component:admincomponent,
  canactivate: [Authguard] ,
  Children: [
   {
    path: ',
    children: [
     {path: ' Crises ', component:managecrisescomponent},< c18/>{path: ' Heroes ', component:manageheroescomponent},
     {path: ', component:admindashboardcomponent}
    ],
   }
  ]
 }
];

Export Const Adminrouting:modulewithproviders = Routermodule.forchild (adminroutes);
Import {injectable} from   ' @angular/core ';
Import {canactivate} from  ' @angular/router ';

@Injectable ()
Export class Authguard implements Canactivate {
 canactivate () {
  console.log (' authguard# Canactivate called ');
  return true;
 }


The Sentinel content involves another part of the knowledge, so I'll put him in the next article.

The ANGULAR2 router allows us to get additional information in the access component other than the current routing parameter. Use the Resolve property in the routing configuration to specify a data distributor.

[
 {
  path: ': Folder ',
  children: [
   {
    path: ',
    component:conversationscmp,
    Resolve: {
     conversations:conversationsresolver
    }
   }
 }]

The data distributor needs to inherit the Dataresolver interface:

@Injectable ()
class Conversationsresolver implements Dataresolver {
 constructor (private repo: Conversationsrepo, Private Currentuser:user) {}

 Resolve (Route:activatedroutesnapshot, State:routestatesnapshot ):
   promise<conversation[]> {return
  this.repo.fetchAll (route.params[' folder '], this.currentuser);
 }
}

You also need to add this data distributor to the providers of module:

@NgModule ({
 //...
 ) Providers: [Conversationsresolver],
 bootstrap: [mailappcmp]
})
class MailModule {
}

Platformbrowserdynamic (). Bootstrapmodule (MailModule);

Then we can access the distribution data through the Activatedroute in the component.

@Component ({
 Template: '
  <conversation *ngfor= "Let C of Conversations | async" ></conversation>
 `
})
Class CONVERSATIONSCMP {
 conversations:observable<conversation[]>;
 Constructor (Route:activatedroute) {
  this.conversations = Route.data.pluck (' conversations ');
 }

Activating components

The routers then instantiate the components based on the routing state and place them on the appropriate routing group starting point.

@Component ({
 template: '
  ...
  ) <router-outlet></router-outlet> ...
  <router-outlet name= "Popup" ></router-outlet>
 '
})
class mailappcmp {
}

such as '/inbox/33/message/44 (Popup:compose) ', first instantiate conversationcmp into main <router-outlet>, The instantiation messagecmp is then placed in the <Router-outlet> of name popup.

Now the router's parsing of the URL is complete. But what if the user wants to jump from the messagecmp to another routing state? ANGULAR2 provides two ways to do this.

One is to navigate through the Router.navigate method:

@Component ({...})
Class MESSAGECMP {
 private id:string;
 Constructor (private Route:activatedroute, private Router:router) {
  Route.params.subscribe (_ => this.id = _.id);
 }

 Openpopup (e) {
  this.router.navigate ([{outlets: {popup: [' message ', This.id]}}]. Then (_ => {
   //navigation is done
  });
 }


One is to use the Router-link method:

@Component {
 Template: '
  <a [routerlink]= ' ['/', {outlets: {popup: [' message ', This.id]}}] ' >edit</ A>
 '
})
class messagecmp {
 private id:string;
 Constructor (private Route:activatedroute) {
  Route.params.subscribe (_ => this.id = _.id);
 }

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.