我很想在Angular 2上设置一个简单的测试应用程序。我有3个页面/组件,我想用新的组件路由器加载。我已经完成了半工作。目前我有两个问题......
1 - 如果您键入要转到Ex的组件的路径。 “http://127.0.0.1:8080/Test2”而不是加载我的Test2页面,它无法说它无法找到该路线。
2 - 尝试加载不同的网页时,我第一次点击链接时,会正确加载网页。当我点击链接时,所有其他页面都会抛出异常。
这是我的设置:
App.ts
import {Component, bootstrap, provide} from 'angular2/angular2';
import {ROUTER_PROVIDERS, ROUTER_DIRECTIVES, RouteConfig, APP_BASE_HREF} from 'angular2/router';
import {Test1} from './Test1';
import {Test2} from './Test2';
import {Test3} from './Test3';
@Component({
selector: 'my-app',
template: '<test1></test1><router-outlet></router-outlet>',
directives: [ROUTER_DIRECTIVES, Test1, Test2]
})
@RouteConfig([
{path: '/', as: 'Home', component: Test1},
{path: '/Test2', as: 'Test2', component: Test2},
{path: '/Test3', as: 'Test3', component: Test3}
])
class AppComponent {
constructor() {}
}
bootstrap(AppComponent, [ROUTER_PROVIDERS, provide(APP_BASE_HREF, { useValue: '/' })]);
Test1.ts
import {Component, bootstrap} from 'angular2/angular2';
import {RouterLink} from 'angular2/router';
@Component({
selector: 'test1',
templateUrl: 'app/Test1.html',
directives: [RouterLink]
})
export class Test1 { }
Test1.html
<h1> Test 1 </h1>
<a [router-link]="['/Test2']">Test Link 2</a>
Test2.ts
import {Component, bootstrap} from 'angular2/angular2';
import {RouterLink} from 'angular2/router';
@Component({
selector: 'test2',
templateUrl: 'app/Test2.html',
directives: [RouterLink]
})
export class Test2 { }
Test2.html
<h1> Test 2 </h1>
<a [router-link]="['/Test3']">Test Link 3</a>
Test3.ts
import {Component, bootstrap} from 'angular2/angular2';
import {RouterLink} from 'angular2/router';
@Component({
selector: 'test3',
templateUrl: 'app/Test3.html',
directives: [RouterLink]
})
export class Test3 { }
Test3.html
<h1> Test 3 </h1>
<a [router-link]="['/Test2']">Test Link 2</a>
感谢帮帮!
Yakov的LocationStrategy建议解决了这个问题。对于有同样问题的人,https://github.com/zorthgo/Angular2QuickstartTest的完整工作代码和我的App.ts的工作版本如下所示:
import {Component, bootstrap, provide} from 'angular2/angular2';
import {ROUTER_PROVIDERS, ROUTER_DIRECTIVES, RouteConfig, APP_BASE_HREF, LocationStrategy, HashLocationStrategy} from 'angular2/router';
import {Test1} from './Test1';
import {Test2} from './Test2';
import {Test3} from './Test3';
@Component({
selector: 'my-app',
template: ` <a [router-link]="['/Home']">Test1 Link</a>
<a [router-link]="['/Test2', {id: 3}]">Test2 Link</a>
<a [router-link]="['/Test3']">Test3 Link</a>
<router-outlet></router-outlet>`,
directives: [ROUTER_DIRECTIVES, Test1, Test2,Test3]
})
@RouteConfig([
{path: '/', component: Test1, as: 'Home'},
{path: '/Test2/:id', component: Test2, as: 'Test2'},
{path: '/Test3', component: Test3, as: 'Test3'}
])
class AppComponent {
constructor() { }
}
bootstrap(AppComponent, [ROUTER_PROVIDERS, provide(LocationStrategy, { useClass: HashLocationStrategy })]);
答案 0 :(得分:5)
我做了类似的事情并且有效。试试这个:
bootstrap(AppComponent, [ROUTER_PROVIDERS, provide(LocationStrategy, {useClass: HashLocationStrategy})]);