In my NativeScript app, I have the route set up as
export const routes = [
{ path: "", component: AppComponent},
{ path: "home", component: HomeComponent},
{ path: "login", component: LoginComponent},
{ path: "news" , component: NewsComponent}
];
After a user is logged in through firebase the user is auto redirected to the HomeComponent
. I should mention that I have a user service that gets fired from the AppComponent Constuctor
that determines if a user is already logged in then redirects them to login or home.
I have console.log() spread across the component to see when things gets triggered so I can try to figure out where to place the code.
import {Component, OnInit} from "@angular/core";
import {Page} from "ui/page";
import {RouterExtensions} from 'nativescript-angular/router';
import firebase = require("nativescript-plugin-firebase");
@Component ({
selector : "home",
templateUrl: "./pages/home/home.html",
styleUrls: ["./pages/home/home.css"]
})
export class HomeComponent implements OnInit {
private router;
constructor(page: Page, router: RouterExtensions) {
console.log("HOME CONSTRUCTOR TRIGGERED");
page.actionBarHidden = false;
this.router = router;
}
ngOnInit(){
console.log("HOME NGONIT TRIGGERED");
}
goToNews(){
this.router.navigate(["/news"]);
}
}
In home.html
I have a button that triggers goToNews()
. When I load up the app, I can see in my console when HomeComponent
constructor gets triggered, but I never see ngOnInit
get triggered. The strange thing is that when I click on the button to navigate to /news
, this is when I see the HomeComponent ngOnInit
fire in my console. Is this the way it's suppose to work?
This all comes down to a "big picture understanding" where I'm trying to figure out the best place to put my logic down when HomeComponent
gets loaded. I read that putting it in the constructor was a bad idea and having it in ngOnInit
is ideal however I don't see how this can make any sense if ngOnInit
only gets triggered after I try to navigate away from the component.
Please help me understand this.
UPDATE: I added a console.log to ngOnInit
in AppComponent
and this does get fired when the app first loads. So it must be the navigation in the services that is causing ngOnInit
to not fire in HomeComponent
.