【问题标题】:Angular 2 - how does a component recognize a URL change? [duplicate]Angular 2 - 组件如何识别 URL 更改? [复制]
【发布时间】:2016-05-12 21:35:03
【问题描述】:

使用 Angular 2,我有一个基于 URL 哈希订阅服务的组件。 URL 更改不会调用任何子组件。我认为这需要 Route,尽管 Location 可能更合适。如何收听弹出状态事件并做出反应?

【问题讨论】:

    标签: angularjs angular angular2-routing


    【解决方案1】:

    如果你想监听路由变化,你可以使用路由器。

    import {Location} from '@angular/common';
    import {Router} from '@angular/router'
    
    export class SomeComponent {
      constructor(router:Router, private location:Location) {
        router.changes.subscribe(() => this.routeChanged());
      }
    
      private routeChanged():void {
        var path:string = this.location.path();
        console.log("Path:" + path);
      }
    }
    

    这是你想做的吗?

    【讨论】:

    • 你在哪里找到Router.changes()?它没有列在Router documentation
    • github.com/angular/angular/blob/…angular.io/docs/ts/latest/api/router/index/… 还显示“changes : Observable<void> 路由器的可观察或 url 更改。”
    • @GünterZöchbauer 运行上述代码时出现错误。代码是否正确编写?我正在运行版本 2.0.0-beta.9。 TypeError: router.changes is undefined
    • 给定的例子是 angular2-rc1 之前它就像 router.subscribe(results => this.routeChanged(results)); private routeChanged(path:string):void { console.log("New Route:" + path); } 你能够从方法参数中获得当前路线,因为 angular2-rc0 我认为它改变了,你只得到一个 void 方法-标题。所以我在注入位置
    • @Sebastian 切换到仅使用 router.subscribe() 会抛出 TypeError: instruction is null。也许解决这个问题的更好方法是解释如何向 Route 添加指令。你能推荐一个最新的教程吗?
    猜你喜欢
    • 2016-02-17
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    • 2012-01-02
    • 2011-09-24
    相关资源
    最近更新 更多