在对象更改时运行代码

时间:2018-08-21 07:57:59

标签: angular typescript angular-ui-router

我希望每次活动状态更改时都运行一段代码。我将值存储为:

export class AdminLayoutComponent implements OnInit, AfterViewInit {
activeState: string;
constructor(private router: UIRouter) {
    this.activeState = this.router.stateService.$current.name;
  }
}

每次当前状态更改时,如何运行一段代码(在导航菜单中为活动状态设置一个类?)?

2 个答案:

答案 0 :(得分:0)

如果几个组件更改一个“变量”,则最容易的是该变量属于服务。然后,在您的组件中使用

get variable(){
    return myservice.variable
}
set variable(value){
    myservice.variable=value
    ...addicional code when we change the variable... 
}
//So in your component you can use
    variable="HellowWord";
//Or in your .html
     {{variable}}

答案 1 :(得分:0)

您正在使用UI-Router库吗?

在这种情况下,我想您需要使用TransitionService钩子。

export class AdminLayoutComponent implements OnInit, AfterViewInit {
  activeState: string;

  constructor(private router: UIRouter) {
    this.activeState = this.router.stateService.$current.name;
  }

  ngOnInit(): void {
    this.router.transitionService.onSuccess({}, (transition: Transition) => {
      this.activeState = this.router.stateService.$current.name;
      return true;
    }
  }
}