开始学习angular2 beta组件路由。到目前为止我已经这样做了。
http://plnkr.co/edit/4YWWGhuBWd2CoWpC3GeY?p=preview
我复制了以下必需的CDN。请看这里。
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.0/angular2-polyfills.js"></script>
<script src="https://rawgithub.com/systemjs/systemjs/0.19.6/dist/system.js"></script>
<script src="https://code.angularjs.org/tools/typescript.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.0/Rx.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.0/angular2.dev.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.0/router.dev.js"></script>
的src / boot.ts
import {Component} from 'angular2/core';
import {ROUTER_PROVIDERS,RouteConfig, ROUTER_DIRECTIVES,LocationStrategy} from 'angular2/router';
import {bootstrap} from 'angular2/platform/browser';
import{ComponentOne} from 'src/cone';
import{ComponentTwo} from 'src/ctwo';
@Component({
selector: 'my-app',
template: `
<h1>Component Router</h1>
<nav>
<a [routerLink]="['ComponentOne']">One</a><hr/>
<a [routerLink]="['ComponentTwo']">Two</a>
</nav>
<router-outlet></router-outlet>
`,
directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
{path:'/component-one', name: 'ComponentOne', component: ComponentOne},
{path:'/component-two', name: 'ComponentTwo', component: ComponentTwo}
])
export class AppComponent { }
bootstrap(AppComponent, [
ROUTER_PROVIDERS
]);
的src /锥体
import {Component,View} from 'angular2/core';
@Component({
template: `
<h1>first Component</h1>
`
})
export class ComponentOne{
constructor(){
console.log("first component being called");
}
}
的src / CTWO
import {Component,View} from 'angular2/core';
@Component({
template: `
<h1>Second Component</h1>
`
})
export class ComponentTwo{
constructor(){
console.log("Second component being called");
}
}
请检查您的开发控制台。它给出了一个错误
EXCEPTION:实例化LocationStrategy时出错! (RouterLink - &gt;路由器 - &gt;位置 - &gt; LocationStrategy).BrowserDomAdapter.logError @ angular2.dev.js:23514 angular2.dev.js:23514原始异常:没有设置基本href。请提供APP_BASE_HREF标记的值或向文档添加基本元素。
此外,它不会将我重定向到目的地。 我试图添加&lt; base href =“/”&gt;但它允许给出错误。
我希望链接能够正常运行。
答案 0 :(得分:15)
将<base href="/">
添加到<head>
元素或将APP_BASE_HREF
添加到bootstrap
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
// usually
provide(APP_BASE_HREF, {useValue: '/'})
// for Plunker
// bind(APP_BASE_HREF).toValue(location.pathname)
]);
答案由Nyks编辑:
在我的plunker中,我更新了以下部分,
import {Component,bind} from 'angular2/core';
import {ROUTER_PROVIDERS,RouteConfig, ROUTER_DIRECTIVES,APP_BASE_HREF,LocationStrategy,RouteParams,ROUTER_BINDINGS} from 'angular2/router';
export class AppComponent { }
bootstrap(AppComponent, [
ROUTER_PROVIDERS,bind(APP_BASE_HREF).toValue(location.pathname)
]);
最终答案:http://plnkr.co/edit/4YWWGhuBWd2CoWpC3GeY?p=preview
另见http://plnkr.co/edit/iRUP8B5OUbxCWQ3AcIDm?p=info
和ROUTING & NAVIGATION developer guide at the angular.io