简体   繁体   English

普通Javascript中的Angular 2路由(无打字稿)

[英]Angular 2 Routing in plain Javascript (No Typescript)

So I have been battling to get the router working in Angular2 without using Typescript. 所以我一直在努力使路由器在Angular2中工作而不使用Typescript。 I can't seem to find any examples, other than some typescript compiled javascript that uses a decorator function. 我似乎找不到任何示例,除了一些使用装饰器函数的打字稿编译的javascript。 Is it possible to use Angular 2 Router with plain Javascript? 可以将Angular 2 Router与纯Javascript一起使用吗?

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/ ): 另一个受Angular2“英雄之旅”教程启发的示例(您可以在此处找到纯JavaScript的完整教程: https ://programming.sereale.fr/2016/03/22/rails-and-angular2-react-the- 英雄之旅/ ):

//= 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';
    }]
});

You can use router.config() method to specify list of routes. 您可以使用router.config()方法指定路由列表。 Here is an example written purely in ES5 (see this plunk ): 这是一个纯粹用ES5编写的示例(请参阅示例):

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). PS 装饰器ES2016 (以前为ES7)的一部分。 They're javascript and supported by Babel . 它们是javascript并受Babel支持。 I think you should not be afraid to use them. 我认为您不应该害怕使用它们。

I too was looking for resources regarding Angular 2 deployment in plain JavaScript. 我也一直在寻找有关以纯JavaScript部署Angular 2的资源。 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.): (IDK为什么,我觉得它真的很有用。)幸运的是,有一种方法可以仅使用Javascript来完成(博客作者的小插曲举例说明了此示例。):

  1. During the bootstrap of your project, include the routes dependencies of Angular's ng.router. 在项目的引导过程中,包括Angular的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 ng: Angular 2库
    app.Main: The main component of the application app.Main:应用程序的主要组件
    ng.router.ROUTER_BINDINGS: includes all the dependencies to use the router. ng.router.ROUTER_BINDINGS:包括使用路由器的所有依赖项。
    ng.core.bind(...): this line is very important if you don't want to handle page reload logic on the server side. ng.core.bind(...):如果您不想在服务器端处理页面重新加载逻辑,此行非常重要。 (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.HomeComponent:配置为示例组件,这将是我们的默认路由。
    app.TestComponent: configured as another example component. app.TestComponent:配置为另一个示例组件。

  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. routerLink:将目标路由通过其名称绑定到链接标记。
    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. 确保将ng.router.ROUTER_DIRECTIVES包含在Main组件的指令中,以便Angular可以识别模板中的指令。

  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. 您的单页面应用程序现在应该仅使用JavaScript就能够处理路由和页面重新加载。

Thanks again to the author of this blog and the time he spent creating this plunk 再次感谢博客的作者以及他花了很多时间创建了这个插件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM