Angular 2 Routing in plain Javascript (No Typescript)

后端 未结 3 1546
北海茫月
北海茫月 2021-01-13 10:31

So I have been battling to get the router working in Angular2 without using Typescript. I can\'t seem to find any examples, other than some typescript compiled javascript th

相关标签:
3条回答
  • 2021-01-13 11:16

    Another example inspired of the Angular2 "Tour of Heroes" tutorial (you can find the full tutorial in plain javascript here: https://programming.sereale.fr/2016/03/22/rails-and-angular2-react-the-tour-of-heroes/):

    //= require directives/dashboard-component
    //= require directives/heroes-component
    //= require directives/hero-detail-component
    //= require services/heroes-service
    
    var MyApp = ng.core.Component({
        selector: 'my-app',
        directives: [ng.router.ROUTER_DIRECTIVES],
        providers: [ng.router.ROUTER_PROVIDERS, ng.http.HTTP_PROVIDERS, HeroService], // ng.http.HTTP_PROVIDERS enables to use http and get the list from the server
        template: "<h1>{{title}}</h1> \
                    <nav> \
                      <a [routerLink]=\"['Heroes']\">Heroes</a> \
                      <a [routerLink]=\"['Dashboard']\">Dashboard</a> \
                    </nav> \
                    <router-outlet></router-outlet>"
    }).Class({
        constructor: [ ng.router.Router, function(router) {
                router.config([
                    { path: '/dashboard', name: 'Dashboard', component: DashboardComponent, useAsDefault: true },
                    { path: '/heroes-list', name: 'Heroes', component: HeroesComponent },                
                    { path: '/detail/:id', name: 'HeroDetail', component: HeroDetailComponent }
                ]);
    
                this.title = 'Tour of Heroes';
        }]
    });
    
    0 讨论(0)
  • 2021-01-13 11:21

    I too was looking for resources regarding Angular 2 deployment in plain JavaScript. I found this article and it was everything I needed to get up and running. Not sure who the author is, but it's very well written and clear.

    The other examples show the use of typescript, which was not allowed in our Enterprise environment. (IDK why, I find it really useful.) Fortunately, there is a way to do it with just Javascript (the blog author's plunk illustrates this example.):

    1. During the bootstrap of your project, include the routes dependencies of Angular's ng.router.

      /*global app*/
      'use strict';
      
      (function (ng, app) {
        document.addEventListener('DOMContentLoaded', function () {
          ng.platform.browser.bootstrap(app.Main , [
            ng.router.ROUTER_BINDINGS,
            ng.core.bind(ng.router.LocationStrategy).toClass(ng.router.HashLocationStrategy)
          ]);
       });
      })(this.ng, this.app);
      

      ng: The Angular 2 Library
      app.Main: The main component of the application
      ng.router.ROUTER_BINDINGS: includes all the dependencies to use the router.
      ng.core.bind(...): this line is very important if you don't want to handle page reload logic on the server side. (Without it or configuring of your hosting server, the browser will request a page that only exists client side due to the single page application routing.)

    2. Configure the router to expose the routes to your application and which components that will handle each of them.

      (function (ng, app) {
      
      ng.router.RouteConfig([
          { path: '/home', component: app.HomeComponent, as: 'Home', useAsDefault: true},
          { path: '/test', component: app.TestComponent, as: 'Test'}
      ])(app.Main);
      
      })(window.ng, window.app);
      

      app.HomeComponent: configured as an example component that will be our default route.
      app.TestComponent: configured as another example component.

    3. Update the links on the main page that will handle the routing:

      <ul>
        <li>
          <a [routerLink]="['Home']">Home</a>
        </li>
        <li>
          <a [routerLink]="['Test']">Test</a>
        </li>
      </ul>
      <router-outlet></router-outlet>
      

      routerLink: binds a target route by it's name to a link tag.
      router-outlet: placeholder for the router to include the different views of components as the user navigates the application.

    4. Ensure you include the ng.router.ROUTER_DIRECTIVES into the directives of your Main component so that Angular can identify the directives in the templates.

    5. Create the components use for the routing:

      //home.component.js
      app.register ('HomeComponent', function (ng) {
        return ng.core.
      
        Component({
          template: '
      <div>Hello {{name}}!</div>
      ',
        }).
        Class({
          constructor:function () {
            this.name ='world';
          }
        });
      
      });
      
      //test.component.js
      app.register ('TestComponent', function (ng) {
        return ng.core.
      
        Component({
          template: 'This is a testing page'
        }).
        Class({
          constructor: function () {}
        });
      
      });
      
    6. Your single page application should now be able to handle both the routing and page reloads using only JavaScript.

    Thanks again to the author of this blog and the time he spent creating this plunk

    0 讨论(0)
  • 2021-01-13 11:24

    You can use router.config() method to specify list of routes. Here is an example written purely in ES5 (see this plunk):

    var App = Component({
      selector: 'my-app',
      directives: [RouterOutlet, RouterLink],
      template: (
        '<h2>Hello, World!!!</h2>' +
        '<ul>' +
          '<li><a [router-link]="[\'./Index\']">Index Page</a></li>' +
          '<li><a [router-link]="[\'./Home\']">Home Page</a></li>' +
        '</ul>' +
        '<router-outlet></router-outlet>'
      )
    })
    .Class({
      constructor: function(router) {
        router.config([
          { path: '/index': component: Index, name: 'Index' },
          { path: '/home':  component: Home,  name: 'Home'  }
        ])
      }
    });
    
    App.parameters = [Router];
    

    PS Decorators are part of ES2016 (formerly ES7). They're javascript and supported by Babel. I think you should not be afraid to use them.

    0 讨论(0)
提交回复
热议问题