【问题标题】:How to watch route change and change value of boolean variable every time route changes in Angular 2?如何在Angular 2中每次路由更改时观察路由更改和布尔变量的更改值?
【发布时间】:2016-08-21 01:35:50
【问题描述】:

我有一个标题组件,我在其中将几个布尔变量设为 true,以使按钮在 html 中可见。所以基本上在 angular 1.x 中,我们在 location.path 上使用 watch。但是在 Angular 2 中,我知道我们没有手表。当我探索更多关于如何实现这一点时,我遇到了变化检测、ngOnChange、Observable、router.subscribe 等主题。我是 Angular 2 的新手,使用的是 Angular 2.0.0-beta.15。我不明白哪个主题我应该阅读以找到解决方案。谁能帮助我哪个主题与我的情况相关?

【问题讨论】:

    标签: routes angular components watch


    【解决方案1】:

    如果您使用的是 3.0.0-beta.2 版本的 @angular/router,他们已经更改了订阅方法

    import {Router} from "@angular/router";
    
    @Component({
    .....
    })
    export class YourCmp {
    
    
        constructor(private router: Router) {
            this.router.events.subscribe(route => {
                console.log(route.url);
            });
        }
    }
    

    【讨论】:

    • 如果您在 之外有一个组件,这会起作用吗?因此,如果我有一个带有按钮的静态导航,如果值为真,我想隐藏/显示,这个 events.subscribe 会广播到该组件吗?
    【解决方案2】:
    import {Router} from 'angular2/router';
    
    @Component({
    .....
    })
    export class YourCmp {
    
       someVar: boolean = false;
    
       constructor(private router: Router){
    
             this.router.subscribe(() => {
               // this code will run on every route change
              // do what you want, here
    
                 this.someVar = !this.someVar;
            });
    
       }    
    }
    

    【讨论】:

    • @A_Singh-你是对的。非常感谢。在发布这个问题之前,我在 subscribe 函数中尝试了与 location.path() 相同的代码。即 this.router.subscribe(location.path() => . 其余一切都与上面相同。但它导致语法错误,我无法理解语法问题是什么。只是解释为有人可能尝试过我做到了,但遇到了麻烦。
    猜你喜欢
    • 2018-09-09
    • 2018-03-30
    • 2017-08-19
    • 2015-03-07
    • 1970-01-01
    • 2016-08-31
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多