我正在使用Angular2种子应用程序,您可以在官方回购中找到它。如您所见,这里导入了angular2 2/路由器,并使用它创建应用程序的基本路由。
import {Component, ViewEncapsulation} from 'angular2/angular2';
import {
RouteConfig,
ROUTER_DIRECTIVES
} from 'angular2/router';
...
@RouteConfig([
{ path: '/', component: HomeCmp, as: 'Home' },
{ path: '/about', component: AboutCmp, as: 'About' }
])
export class AppCmp {}我的问题是:如何配置路由器以在我的url中添加hashtag,使其看起来像:localhost:5555/#/关于。有什么漂亮简单的方法吗?(与前面的$locationProvider一样)
我知道这很奇怪,但是我以前喜欢这个url中的标签,我的apache-config也喜欢它。当然,我可以更改我的httpd.conf文件,非常简单和正确,但我真的想弄清楚,如何简单地添加Angular2标签,使用Angular2路由器。
发布于 2015-10-20 01:15:12
在应用程序启动文件中,您需要在调用引导程序时提供位置策略,
import {LocationStrategy, HashLocationStrategy} from 'angular2/router';
class MyDemoApp {
//your code
}
bootstrap(MyDemoApp,[provide(LocationStrategy, {useClass: HashLocationStrategy})]);发布于 2019-05-03 15:50:23
对于任何有同样问题但不使用角种子的人:
navigateToSomeLocation(location: string){
window.location.href = "#" + location;
}如果使用角材料,并且希望订阅滚动事件以更改url (如此处:https://material.io/design/navigation/understanding-navigation.html#),请订阅ScrollDispatcher:
constructor(public scrollDispatcher: ScrollDispatcher) {
this.scrollingSubscription = this.scrollDispatcher.scrolled()
.subscribe((data: CdkScrollable) => {
console.log(window.pageYOffset);
});
}然后检查用户是否在锚上滚动:
elem = document.getElementById('someHTMLElement') as HTMLElement;
distance = elem.getBoundingClientRect().top;
if (distance < 30 && distance > -30) {
this.navigateToSomeLocation(elem.id);
}有关参考资料,请参阅:手动滚动到锚时更改url?
https://stackoverflow.com/questions/33226286
复制相似问题