4

我正在使用 Angular2 Seed 应用程序,您可以在官方 repo中找到它。如您所见,这里我们导入了 angular2/router,我们使用它来创建应用程序的基本路由。

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 {}

我的问题是:如何配置路由器以在我的网址中添加主题标签,使其看起来像: localhost:5555/#/about。有没有什么漂亮又简单的制作方法?(和之前的 $locationProvider 一样)

我知道这很奇怪,但我曾经喜欢 url 中的这个标签,我的 apache-config 也曾经喜欢它。当然,我可以更改我的 httpd.conf 文件,非常简单且正确,但我真的很想弄清楚,如何使用 Angular2 路由器简单地添加主题标签。

4

3 回答 3

7

在您的应用程序启动文件中,您需要在调用引导程序时提供位置策略,

import {LocationStrategy, HashLocationStrategy} from 'angular2/router';

class MyDemoApp {
    //your code
}

bootstrap(MyDemoApp,[provide(LocationStrategy, {useClass: HashLocationStrategy})]);
于 2015-10-20T01:15:12.050 回答
1

要在 Angular 路由中使用主题标签,您可以这样做:RouterModule.forRoot(routes,{ useHash: true })

于 2020-04-11T07:37:58.690 回答
1

对于有同样问题但不使用 Angular Seed 的任何人:

navigateToSomeLocation(location: string){
  window.location.href = "#" + location;
}

如果您使用 Angular Material 并且想要订阅滚动事件以更改 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?

于 2019-05-03T15:50:23.663 回答