Ionic: How to use nav controller in app.component.ts - ionic-framework

I am trying to develop an app in ionic 5. I added side menus in app.component.html along with ion-router-outlet. Now I want to navigate from side menus to my pages. I tried using router.navigate(['path']).
It navigates correctly, but the ion-back-button is not working on the navigated page.
These are my dependencies and version:
"dependencies": {
"#angular/common": "~10.0.0",
"#angular/core": "~10.0.0",
"#angular/forms": "~10.0.0",
"#angular/platform-browser": "~10.0.0",
"#angular/platform-browser-dynamic": "~10.0.0",
"#angular/router": "~10.0.0",
"#ionic-native/core": "^5.0.0",
"#ionic-native/splash-screen": "^5.0.0",
"#ionic-native/status-bar": "^5.0.0",
"#ionic/angular": "^5.0.0",
"cordova-android": "8.1.0",
"rxjs": "~6.5.5",
"tslib": "^2.0.0",
"zone.js": "~0.10.3"
}
my app.component.html
<ion-menu *ngIf="isSideDrawerAllowed()" side="start" menuId="first" contentId="main">
<ion-header>
<ion-toolbar translucent>
<ion-title>Menu</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<!-- <ion-item (click)="navigateTo('/about-us')"> -->
<ion-item [routerLink]="['/about-us']">
<ion-icon name="mail" slot="start"></ion-icon>
<ion-label>About me</ion-label>
</ion-item>
<ion-item (click)="navigateTo('/schedule')">
<ion-icon name="paper-plane" slot="start"></ion-icon>
<ion-label>Schedule</ion-label>
</ion-item>
<ion-item (click)="navigateTo('/news')">
<ion-icon name="heart" slot="start"></ion-icon>
<ion-label>News</ion-label>
</ion-item>
<ion-item (click)="navigateTo('/gallary')">
<ion-icon name="archive" slot="start"></ion-icon>
<ion-label>Gallary</ion-label>
</ion-item>
</ion-list>
</ion-content>
</ion-menu>
<ion-router-outlet id="main"></ion-router-outlet>
app.component.ts
import { Component, OnInit, QueryList, ViewChildren } from '#angular/core';
import { Platform, AlertController, IonRouterOutlet, ToastController, NavController } from '#ionic/angular';
import { SplashScreen } from '#ionic-native/splash-screen/ngx';
import { StatusBar } from '#ionic-native/status-bar/ngx';
import { Router, RouterModule } from "#angular/router";
import { Location } from '#angular/common';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent {
#ViewChildren(IonRouterOutlet) routerOutlets: QueryList<IonRouterOutlet>;
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private alertController: AlertController,
private toastController: ToastController,
private router: Router,
private location: Location
) {
this.initializeApp();
}
initializeApp() {
console.log('initializeApp')
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
isSideDrawerAllowed() {
let allowedRoutes = ["/", "/home"]
return allowedRoutes.includes(this.router.url)
}
navigateTo(url) {
this.router.navigateByUrl(url)
}
}
Please help me.

You don't need router or allowed routes. Your routes should already be set-up in app-routing.module.ts. Since you are not calling the ionic nav controller your URLs are not being added to the stack and so the back function does not work. navController knows about routes set-up in your routing modules.
Do this:
import { Component, OnInit } from '#angular/core';
import { Platform, NavController } from '#ionic/angular';
import { SplashScreen } from '#ionic-native/splash-screen/ngx';
import { StatusBar } from '#ionic-native/status-bar/ngx';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent {
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private navController: NavController
) {
this.initializeApp();
}
initializeApp() {
console.log('initializeApp')
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
navigateTo(url) {
this.navController.navigateForward(url);
}
}

NavController is deprecated as of Ionic 4, try using ion-nav (Nav).

Related

ion-tabs displaying, but not switching to other tabs

I couldn't find a question that helps me.
I've this on every one of my pages. The navbar is displaying, but the buttons aren't switching to other tabs. This is quite literally copied from the ionic start myApp tabs.
This is one of the pages:
<ion-header>
<ion-toolbar>
<ion-title>Playlists</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
</ion-content>
<ion-tabs>
<ion-tab-bar slot="bottom">
<ion-tab-button tab="saved">
<ion-icon name="heart"></ion-icon>
<ion-label>Saved</ion-label>
</ion-tab-button>
<ion-tab-button tab="search">
<ion-icon name="search"></ion-icon>
<ion-label>Search</ion-label>
</ion-tab-button>
<ion-tab-button tab="playlists">
<ion-icon name="list"></ion-icon>
<ion-label>Playlists</ion-label>
</ion-tab-button>
</ion-tab-bar>
</ion-tabs>
And this is my app-routing.modules.ts file:
import { NgModule } from '#angular/core';
import { PreloadAllModules, RouterModule, Routes } from '#angular/router';
const routes: Routes = [
{ path: '', redirectTo: 'saved', pathMatch: 'full' },
{ path: 'saved', loadChildren: './pages/saved/saved.module#SavedPageModule' },
{ path: 'search', loadChildren: './pages/search/search.module#SearchPageModule' },
{ path: 'playlists', loadChildren: './pages/playlists/playlists.module#PlaylistsPageModule' }
];
#NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule {}
Just went with the default tabs template again, you need a tabs router. I hadn't made any progress so it's fine.

Uncaught Error: Template parse errors in ionic when adding navigation

I have this app I am building in Ionic and I tried adding navigation buttons from home page to both login and registration pages but when I add function (click)=”loginPage()” an error occured.
Below is the screenshot of the error:
App.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { LoginPage } from '../pages/login/login';
import { RegisterPage } from '../pages/register/register';
#NgModule({
declarations: [
MyApp,
HomePage,
LoginPage,
RegisterPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
LoginPage,
RegisterPage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
home.ts
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { LoginPage } from '../login/login';
import { RegisterPage } from '../register/register';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController, public navParams: NavParams) {
}
loginPage(){
this.navCtrl.push(LoginPage);
}
registerPage(){
this.navCtrl.push(RegisterPage);
}
}
And home.html
<ion-content padding class="home">
<ion-grid>
<ion-row>
<ion-col col-12 class="div-two">Welcome</ion-col>
</ion-row>
<ion-row justify-content-start>
<ion-col col-6 class="col">
<div><button ion-button round (click)=”loginPage()”>Login</button></div>
</ion-col>
<ion-col col-6 class="col">
<div><button ion-button round (click)=”registerPage()”>Register</button></div>
</ion-col>
</ion-row>
</ion-grid>
</ion-content>
I have tried all I could but still don't know what the cause of the error is. i am new to ionic.
Thanks.
Your double quote charater is invalid. Do not use ”loginPage()” but use "loginPage()".
This sometimes happens when you copy some code to editor directly. Please be careful about that.

Ionic streaming media plugin issue

I'm trying to build an ionic app to stream audio feeds.
Here's what I have so far...
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { StreamingMedia } from '#ionic-native/streaming-media';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
#NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
StreamingMedia,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
home.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { StreamingMedia, StreamingAudioOptions } from '#ionic-native/streaming-media';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController, private streamingMedia: StreamingMedia) {
}
playStream() {
let options: StreamingAudioOptions = {
bgColor: 'red',
successCallback: () => { console.log('Audio played') },
errorCallback: (e) => { console.log('Error streaming') }
};
this.streamingMedia.playAudio('http://listen.radionomy.com:80/NewYorkClassicRock');
}
}
home.html
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
The world is your oyster.
<p>
If you get lost, the docs will be your guide.
</p>
<button ion-button large (click)="playStream()">Start the Stream!</button>
</ion-content>
Using ionic view, clicking the button does nothing in android or ios.
What am I doing wrong or missing?
Thanks!
It will not work in ionic view.
Run it on a physical device using the command:
cordova run android --debug
from within your app folder !
One small observation, you are setting the options but not passing it to the streamingMedia. You might want to do this:
this.streamingMedia.playAudio('http://listen.radionomy.com:80/NewYorkClassicRock',options);

Ionic 2 Yelp API

I'm trying to connect an Ionic 2 app to Yelp's API. Right now I'm just using a blank Ionic 2 application generated from the CLI and running on my localhost.
My code:
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { HttpModule } from '#angular/http';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
#NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
HttpModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
home.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Http } from '#angular/http';
import { Headers, RequestOptions } from '#angular/http';
import 'rxjs/add/operator/map';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
restaurants:any;
constructor(public navCtrl: NavController, public http: Http) {
var headers = new Headers();
headers.append('Authorization', 'Bearer someString');
var options = new RequestOptions({headers: headers});
this.http.get('https://api.yelp.com/v3/businesses/search?term=deli20&latitude=39.59754&longitude=-104.872934', options).map(res => res.json()).subscribe(data => {
this.restaurants = data.data.children;
console.log(this.restaurants);
});
}
}
home.html
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
The world is your oyster.
<p>
If you get lost, the docs will be your guide.
</p>
<!--Just using Ionic 2's default home page, just wanna output my JSON to the console for now.-->
</ion-content>
The page renders correctly, but the error I get in the console: "Failed to load resource: Preflight response is not successful"
The response looks like this:
{"error": {"code": "TOKEN_MISSING", "description": "An access token must be supplied in order to use this endpoint."}}
Any thoughts on what I might be missing?
Add this chrome plugin to your browser, turn it on and reload the page. It should work fine

Ionic 2 form wont capture form values

So I have a form that looks like this. Each input field is the same so theres no need to post all 241 of them.
My problem is that I cant access the from values through something like formData.general_information_first_name because it return "" nothing.
All of my fields are returning invalid even when the requirements have been met.
<ion-content>
<form #formData="authForm" (submit)="onSubmit(authForm.value)">
<ion-item-group>
<!-- <button light block >{{'HOME | translate'}}</button> -->
<ion-item-divider light>{{'INFORMATION_TO_COMPLETE_LOAN_APPLICATION' | translate}}</ion-item-divider>
<ion-item>
<ion-label fixed="first_name">{{'FIRST_NAME' | translate}}</ion-label>
<ion-input ngControl="general_information_first_name" type="text" value=""></ion-input>
</ion-item>
</ion-content>
My corresponding .ts file
import {Component} from "#angular/core";
import {TranslatePipe} from "ng2-translate/ng2-translate";
import {FORM_DIRECTIVES, FormBuilder, ControlGroup, Validators, AbstractControl} from '#angular/common';
import {CustomValidators} from './custom-validators';
#Component({
templateUrl: 'build/pages/us-loan/us-loan.html',
pipes: [TranslatePipe],
directives: [FORM_DIRECTIVES]
})
export class UsCitizenPage {
authForm: ControlGroup;
general_information_first_name: AbstractControl;
constructor(private fb: FormBuilder) {
this.authForm = this.fb.group({
'general_information_first_name': ['', Validators.compose([Validators.required, CustomValidators.onlyLetters])]
});
this.general_information_first_name = this.authForm.controls['general_information_first_name'];
}
onSubmit(formData) {
console.log('Form submitted is ', formData);
debugger;
if(this.authForm.valid) {
console.log('Submitted value: ', formData);
debugger;
}
}
my angular and ionic version information :
{
"dependencies": {
"#angular/common": "2.0.0-rc.3",
"#angular/compiler": "2.0.0-rc.3",
"#angular/core": "2.0.0-rc.3",
"#angular/http": "2.0.0-rc.3",
"#angular/platform-browser": "2.0.0-rc.3",
"#angular/platform-browser-dynamic": "2.0.0-rc.3",
"es6-shim": "^0.35.0",
"ionic-angular": "2.0.0-beta.10",
"ionic-native": "1.3.2",
"ionicons": "3.0.0",
"ng2-translate": "^2.2.2",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.6",
"zone.js": "^0.6.12"
},
"devDependencies": {
"del": "2.2.0",
"gulp": "^3.9.1",
"gulp-uglify": "^2.0.0",
"gulp-watch": "4.3.5",
"ionic-gulp-browserify-typescript": "2.0.0",
"ionic-gulp-fonts-copy": "^1.0.0",
"ionic-gulp-html-copy": "^1.0.0",
"ionic-gulp-sass-build": "^1.0.0",
"ionic-gulp-scripts-copy": "^2.0.0",
"run-sequence": "1.1.5"
},
}