【问题标题】:Angular2 Router: add hashtag to urlAngular2路由器:将标签添加到url
【发布时间】:2016-01-18 12:01:06
【问题描述】:

我正在使用 Angular2 Seed 应用程序,您可以在 official 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 路由器简单地添加主题标签。

【问题讨论】:

    标签: angular angular-routing angular-seed


    【解决方案1】:

    在你的应用启动文件中,调用bootstrap时需要提供locationstrategy,

    import {LocationStrategy, HashLocationStrategy} from 'angular2/router';
    
    class MyDemoApp {
        //your code
    }
    
    bootstrap(MyDemoApp,[provide(LocationStrategy, {useClass: HashLocationStrategy})]);
    

    【讨论】:

    【解决方案2】:

    对于有同样问题但不使用 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);
      }
    

    参考见:Change url when manually scrolled to an anchor?

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2015-01-25
        • 2017-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-28
        • 2021-06-12
        • 2019-05-03
        相关资源
        最近更新 更多