在ui-router-ng2中以编程方式导航到路由

时间:2016-09-29 15:46:55

标签: angular angular-ui-router

我在Angular 2应用中使用ui-router-ng2。如何告诉路由器从JavaScript / Typescript导航到状态?我正在寻找类似的东西:

export class SomeClass {
    constructor(private router: UIRouter) { }
    somefunc() {
        if (some condition) {
            this.router.navigate("/whatever")
        } else {
            this.router.navigate("/home")
    }
}

2 个答案:

答案 0 :(得分:1)

这应该使用州名而不是网址。

import {UIRouter} from "ui-router-ng2";

export class SomeClass {

  constructor (private _uiRouter:UIRouter) {}

  somefunc() {
    if (some condition) {
      this._uiRouter.stateService.go('whatever')
    } else {
      this._uiRouter.stateService.go('home')
    }
  }

}

答案 1 :(得分:0)

我建议使用依赖注入来访问StateService

在角度component

中尝试此操作
import { Component, OnInit } from "@angular/core";
import { StateService } from "@uirouter/core";

@Component({selector: "app-component-name",})

export class SomeComponent implements OnInit {
    constructor(private stateService: StateService) { }    
    ngOnInit() {}
    public someFunction(){
        this.stateService.go('your_named_state');
    }
}