user2094257
user2094257

Reputation: 1715

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

i'm working on a very basic barcodescanner and having some issues rooting to a view from a controller. In my app.component.ts in the ngOnInit() function I check whether a local IP has been saved in Application-settings and if it hasn't been set the app should root to a settings view where the IP can be set. When I use [nsRouterLink] to navigate to the settings view it works fine but I don't seem to be able to do this programatically... Any idea what i'm doing wrong?

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
];

Upvotes: 0

Views: 438

Answers (2)

AVJT82
AVJT82

Reputation: 73377

Complete edit of my question. I think I found your problem now. The problem most likely is that you are trying to navigate from AppComponent, where you have your router-outlets. Therefore ngOnInit is fired, but not navigating.

Well now... OP found just now out the solution, as I was writing this post... :D

Upvotes: 1

Habeeb
Habeeb

Reputation: 1040

There are some difference in route implementation between angular and nativescript. Instead of importing for angular route, you have to import from nativescript route

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

on constructor

constructor(private router: RouterExtensions) {
}

then try this

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

Upvotes: 0

Related Questions