ngOnInit doesn't run until after I navigate to another component - nativescript

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.

Try putting the router.navigate() into a separate "Zone":
import:
import { NgZone } from "#angular/core";
inject:
constructor(private zone: NgZone) { ... }
apply:
this.zone.run(() => {
this.router.navigate(["/news"]);
});
found here.

Related

MSTeams Config page Angular 12 SPA with routing

I'm using Angular 12 and am writing a simple group tab app. I'm working on the config page component and the html looks like this:
<br />
<br />
<br />
<p>Configuration 3</p>
<input type="text" placeholder="Some Test" />
In a normal browser, the text and box appears. But if I try to do the same thing via the install to tab path, I don't get the text or input box at all.
I think this might have something to do with routing but can't confirm.
The app-routing-module is pretty simple:
const routes: Routes = [
{
path: '',
component: HomeComponent,
},
{
path: 'configuration',
component: ConfigurationComponent,
},
];
#NgModule({
imports: [
RouterModule.forRoot(routes, {
initialNavigation:
!BrowserUtils.isInIframe() && !BrowserUtils.isInPopup()
? 'enabled'
: 'disabled',
}),
],
exports: [RouterModule],
})
export class AppRoutingModule {}
So what does it take to get the SPA to route to the configuration page when used within teams?
Configuration Component: (URL purposed changed to protect the innocent)
import { Component, OnInit } from '#angular/core';
import { Inject, AfterViewInit, ElementRef } from '#angular/core';
import { DOCUMENT } from '#angular/common';
import * as microsoftTeams from '#microsoft/teams-js';
#Component({
selector: 'app-configuration',
templateUrl: './configuration.component.html',
styleUrls: ['./configuration.component.scss'],
})
export class ConfigurationComponent implements OnInit, AfterViewInit {
constructor(
#Inject(DOCUMENT) private document: Document,
private elementRef: ElementRef
) {}
ngOnInit(): void {
microsoftTeams.initialize();
}
ngAfterViewInit() {
console.log('Initializing ms teams');
microsoftTeams.settings.registerOnSaveHandler((saveEvent) => {
microsoftTeams.settings.setSettings({
entityId: '',
contentUrl: 'https://test.ngrok.io',
suggestedDisplayName: 'Test',
websiteUrl: 'https://test.ngrok.io',
});
saveEvent.notifySuccess();
});
console.log('Register on save');
microsoftTeams.settings.setValidityState(true);
}
}
Thanks,
Nick
In order to render a tab in Teams. You need to make sure that it is iFramable. Please see the document- Tab requirements.
Make sure that you have given the domain in valid domains in your manifest.
Please share more details like console error, what are you using static tab or config and manifest, if issue isn't solve for you
I traced my problem for this particular question to the line:
initialNavigation:
!BrowserUtils.isInIframe() && !BrowserUtils.isInPopup()
? 'enabled'
: 'disabled',
This example is in a lot of the code for SPAs in and Teams Tabs.
I just have it set to 'enabled' for now and I can get beyond the purpose of this question.

Possible memory leak in NativeScript app if user reopens his app multiple times

I'm not sure where is the bug, maybe I'm using rxjs in a wrong way. ngDestroy is not working to unsubscribe observables in NativeScript if you want to close and back to your app. I tried to work with takeUntil, but with the same results. If the user close/open the app many times, it can cause a memory leak (if I understand the mobile environment correctly). Any ideas? This code below it's only a demo. I need to use users$ in many places in my app.
Tested with Android sdk emulator and on real device.
AppComponent
import { Component, OnDestroy, OnInit } from '#angular/core';
import { Subscription, Observable } from 'rxjs';
import { AppService } from './app.service';
import { AuthenticationService } from './authentication.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnDestroy, OnInit {
public user$: Observable<any>;
private subscriptions: Subscription[] = [];
constructor(private appService: AppService, private authenticationService: AuthenticationService) {}
public ngOnInit(): void {
this.user$ = this.authenticationService.user$;
this.subscriptions.push(
this.authenticationService.user$.subscribe((user: any) => {
console.log('user', !!user);
})
);
}
public ngOnDestroy(): void {
if (this.subscriptions) {
this.subscriptions.forEach((subscription: Subscription) => subscription.unsubscribe());
}
}
async signIn() {
await this.appService.signIn();
}
async signOut() {
await this.appService.signOut();
}
}
AuthenticationService
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { shareReplay } from 'rxjs/operators';
import { AppService } from './app.service';
#Injectable({
providedIn: 'root',
})
export class AuthenticationService {
public user$: Observable<any>;
constructor(private appService: AppService) {
this.user$ = this.appService.authState().pipe(shareReplay(1)); // I'm using this.users$ in many places in my app, so I need to use sharereplay
}
}
AppService
import { Injectable, NgZone } from '#angular/core';
import { addAuthStateListener, login, LoginType, logout, User } from 'nativescript-plugin-firebase';
import { BehaviorSubject, Observable } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';
const user$ = new BehaviorSubject<User>(null);
#Injectable({
providedIn: 'root',
})
export class AppService {
constructor(private ngZone: NgZone) {
addAuthStateListener({
onAuthStateChanged: ({ user }) => {
this.ngZone.run(() => {
user$.next(user);
});
},
});
}
public authState(): Observable<User> {
return user$.asObservable().pipe(distinctUntilChanged());
}
async signIn() {
return await login({ type: LoginType.PASSWORD, passwordOptions: { email: 'xxx', password: 'xxx' } }).catch(
(error: string) => {
throw {
message: error,
};
}
);
}
signOut() {
logout();
}
}
ngOnDestroy is called whenever a component is destroyed (following regular Angular workflow). If you have navigated forward in your app, previous views would still exist and would be unlikely to be destroyed.
If you are seeing multiple ngOnInit without any ngOnDestroy, then you have instantiated multiple components through some navigation, unrelated to your subscriptions. You should not expect the same instance of your component to be reused once ngOnDestroy has been called, so having a push to a Subscription[] array will only ever have one object.
If you are terminating the app (i.e. force quit swipe away), the whole JavaScript context is thrown out and memory is cleaned up. You won't run the risk of leaking outside of your app's context.
Incidentally, you're complicating your subscription tracking (and not just in the way that I described above about only ever having one pushed). A Subscription is an object that can have other Subscription objects attached for termination at the same time.
const subscription: Subscription = new Subscription();
subscription.add(interval(100).subscribe((n: number) => console.log(`first sub`));
subscription.add(interval(200).subscribe((n: number) => console.log(`second sub`));
subscription.add(interval(300).subscribe((n: number) => console.log(`third sub`));
timer(5000).subscribe(() => subscription.unsubscribe()); // terminates all added subscriptions
Be careful to add the subscribe call directly in .add and not with a closure. Annoyingly, this is exactly the same function call to make when you want to add a completion block to your subscription, passing a block instead:
subscription.add(() => console.log(`everybody's done.`));
One way to detect when the view comes from the background is to set callbacks on the router outlet (in angular will be)
<page-router-outlet
(loaded)="outletLoaded($event)"
(unloaded)="outletUnLoaded($event)"></page-router-outlet>
Then you cn use outletLoaded(args: EventData) {} to initialise your code
respectively outletUnLoaded to destroy your subscriptions.
This is helpful in cases where you have access to the router outlet (in App Component for instance)
In case when you are somewhere inside the navigation tree you can listen for suspend event
Application.on(Application.suspendEvent, (data: EventData) => {
this.backFromBackground = true;
});
Then when opening the app if the flag is true it will give you a hint that you are coming from the background rather than opening for the first time.
It works pretty well for me.
Hope that help you as well.

NativeScript vue, vuex and urlhandler

Edit
I'm using https://github.com/hypery2k/nativescript-urlhandler to open a deep link within my app - using NativeScript vue, and vuex. It seems that in order to get at the methods needed to do routing [$navigateTo etc] this plugin needs to be set up slightly differently from the examples given in docs.
import Vue from "nativescript-vue";
import Vuex from "vuex";
Vue.use(Vuex);
import { handleOpenURL } from 'nativescript-urlhandler';
new Vue({
mounted() {
handleOpenURL( (appURL) => {
console.log(appURL)
// Settings is the variable that equals the component - in this case settings.
this.$navigateTo(Settings);
});
},
render: h => h("frame", [h(Home)]),
store: ccStore
}).$start();
handleOpenURL needs to be called within Mounted - then you can parse out the appURL and reference the page (component) that you wish to navigate to. I have been advised against calling handleOpenURL from within router - but I'm not sure why, and it works without error - and I have access to the methods for routing... so if anyone knows if this is a bad idea - please let me know :) Thanks!
All the stuff below that I wrote before has probably confused things - I'm referencing components within my vuex store to make them easily available from the router.
This is based on a solution by https://github.com/Spacarar - it can be found here: https://github.com/geodav-tech/vue-nativescript-router-example. It's a great solution because you don't have to include every single component within each component to use in navigation - it gives an almost vue router like experience.
I'm using https://github.com/hypery2k/nativescript-urlhandler to open a deep link within my app - however, I'm having problems opening the link.
In my app.js file, I have the following:
import Vue from "nativescript-vue";
import Vuex from "vuex";
Vue.use(Vuex);
....
import { handleOpenURL } from 'nativescript-urlhandler';
import ccStore from './store/store';
handleOpenURL(function(appURL) {
// I have hardwired 'Settings' in for testing purposes - but this would be the appURL
ccStore.dispatch('openAppURL', 'Settings');
});
....
new Vue({
render: h => h("frame", [h(Home)]),
store: ccStore
}).$start();
I'm storing the route state within vuex, and have various methods which work (clicking on a link loads the component). However, handleOpenURL exists outside of vue... so I've had to access vuex directly from within the handleOpenURL method. I've created an action specifically for this case - openAppURL.. it does exactly the same thing as my other methods (although I've consolidated it).
When clicking on an app link, I am NOT taken to the page within the app. I have put a console log within openAppURL and can see it is being called, and the correct route object is returned... it just doesn't open the page. The SetTimeOut is used because nextTick isn't available from within vuex.
I am at a loss on how to get the page to appear...
const ccStore = new Vuex.Store({
state: {
user: {
authToken: null,
refreshToken: null,
},
routes: [
{
name: "Home",
component: Home
},
{
name: "Log In",
component: Login
},
...
],
currentRoute: {
//INITIALIZE THIS WITH YOUR HOME PAGE
name: "Home",
component: Home //COMPONENT
},
history: [],
},
mutations: {
navigateTo(state, newRoute, options) {
state.history.push({
route: newRoute,
options
});
},
},
actions: {
openAppURL({state, commit}, routeName ) {
const URL = state.routes[state.routes.map( (route) => {
return route.name;
}).indexOf(routeName)];
return setTimeout(() => {
commit('navigateTo', URL, { animated: false, clearHistory: true });
}, 10000);
},
....
}
etc....
I have been advised to post my findings as the answer and mark it as correct. In order to use nativescript-urlhandler with vue, you must initialise the handler from within vue's mounted life cycle hook. Please see above for greater detail.
import Vue from "nativescript-vue";
import Vuex from "vuex";
Vue.use(Vuex);
import Settings from "~/components/Settings";
import { handleOpenURL } from 'nativescript-urlhandler';
new Vue({
mounted() {
handleOpenURL( (appURL) => {
console.log(appURL) // here you can get your appURL path etc and map it to a component... eg path === 'Settings. In this example I've just hardwired it in.
this.$navigateTo(Settings);
});
},
render: h => h("frame", [h(Home)]),
store: ccStore
}).$start();

handling link opening event in HtmlView

I have a html code that has a link inside it. code below is my template:
<HtmlView [html]="htmlString" ></HtmlView>
this is my component:
import { Component } from "#angular/core";
#Component({
moduleId: module.id,
templateUrl: "./creating-htmlview.component.html"
})
export class CreatingHtmlViewExampleComponent {
public htmlString: string;
constructor() {
this.htmlString = 'google';
}
}
how to handle a element inside of HtmlView when it run ? there is a way to detect when user run the link?
That's not supported yet, there is an open feature request. You may write a plugin that implements native apis like ClickableSpan or Linkify.

Nativescript update http response when app launches

I have an app I have inherited that is getting data from an API endpoint. We have found that when we change data on the API, the changes are not reflected in the app. If we uninstall and re-install the app on a mobile device, then the new data from the API is displayed. Here is an example of the Building Detail page:
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from "#angular/router";
import { switchMap } from 'rxjs/operators';
import { Building } from "../shared/building/building";
import { HttpService } from "../services/http/http.service";
import {
getString,
setString
} from "application-settings";
#Component({
moduleId: module.id,
selector: 'building-detail',
templateUrl: 'building-detail.component.html',
styleUrls: ["./building-detail-common.css"],
providers: [ Building, HttpService ]
})
export class BuildingDetailComponent implements OnInit {
paramName: string;
constructor(
private route: ActivatedRoute,
public building: Building,
private httpService: HttpService) {
this.route.params.subscribe(
(params) => {
this.paramName = params['name']
}
);
}
ngOnInit() {
console.log("ON INIT FIRED " + this.paramName);
let buildingInfo = JSON.parse(getString("buildingInfo"));
for (let item of buildingInfo) {
if (item.attributes.title === this.paramName) {
this.building.name = item.attributes.title;
this.building.desc = item.attributes.body.value;
let imageEndpoint = "file/file/" + item.relationships.field_building_image.data.id;
let imageUrl = this.httpService.getData(imageEndpoint)
.subscribe(data => {
this.building.image = "https://nav.abtech.edu" + data['data'].attributes.url;
console.log("The building image URL is " + this.building.image);
}, (error) => {
console.log("Error is " + error);
});
}
}
}
}
I am happy to share other files/code if you would like to look at those. Thanks!
The reason your data is not being updated is not because the ngOnInit is not being executed, it's because you're caching the old value and reloading it each time the app is run. You're caching the data persistently across app runs with appSettings and that's why you are seeing the values stay the same until you uninstall.
If you don't want to show a cached value then don't read from the app settings, or at least don't read from appSettings until you've refreshed the data once.
ngOnInit is something that is executed only when your component is created, it will never be executed again.
Also there is difference between app launch and resume, if you want to update data every time when user opens the app, you should listen to resume event and perform apis calls inside ngZone
You may even use push notification / data message if you want to notify user immediately when data changes on backend

Resources