Angular2/Nativescript: 无法以编程方式从组件控制器路由到视图

Angular2/Nativescript: Unable to route to a view programatically from component controller

我正在开发一个非常基本的条形码扫描器,但在从控制器获取视图时遇到了一些问题。在 ngOnInit() 函数的 app.component.ts 中,我检查本地 IP 是否已保存在应用程序设置中,如果尚未设置,应用程序应根目录到可以设置 IP 的设置视图。当我使用 [nsRouterLink] 导航到设置视图时,它工作正常,但我似乎无法以编程方式执行此操作...知道我做错了什么吗?

app.component.ts:

    import { Component, OnInit } from "@angular/core";
    import { Router } from '@angular/router';
    import { RestService } from './services/rest.service';
    import { AppSettingsService } from './services/app-settings.service';


    @Component({
        selector: "main",
        template : "<page-router-outlet></page-router-outlet>"
    })
    export class AppComponent implements OnInit {

        constructor(private restService: RestService, private appSettingsService: AppSettingsService, private router: Router) {

        }

        ngOnInit() {

      let ip = this.appSettingsService.findLocalIP();
      if (ip !== null) {
          this.restService.init(ip);
      } else if (ip === null) {
          console.log("ip: " + ip);
          this.router.navigate(['settings']);
      }

    }

    }

app.routing.ts:

import { AppComponent } from './app.component';
import { HomeComponent } from './pages/home/home.component';
import { CheckBarcodesComponent } from './pages/check-barcodes/check-barcodes.component';
import { SettingsComponent } from './pages/settings/settings.component';

export const routes = [
    {path: "", component: HomeComponent},
        {path: "checkBarcodes", component: CheckBarcodesComponent},
            {path: "settings", component: SettingsComponent}
];

export const navigatableComponents = [
HomeComponent,
CheckBarcodesComponent,
SettingsComponent
];

angular 和 nativescript 在路由实现上有一些不同。您必须从 nativescript 路由导入,而不是导入 angular 路由

import { RouterExtensions, PageRoute } from "nativescript-angular/router";

关于构造函数

constructor(private router: RouterExtensions) {
}

那就试试这个

 this.router.navigate(['settings']);

完成我的问题编辑。我想我现在发现了你的问题。问题很可能是您正试图从 AppComponent 导航,那里有您的路由器插座。因此 ngOnInit 被触发,但没有导航。

那么现在......OP 刚刚找到了解决方案,因为我正在写这篇文章 post......:D