[SOLVED] - Updating the url when pushing page on the nav stack


#1

Hello,

I’m creating a new topic on this as several of us have waited months to have this feature and on the surface it looks like it’s been resolved, but it doesn’t quite appear that way. I’m currently migrating from Beta 6 to RC.1 and for the most part things are working (other than the routing).

Can someone from the Ionic team provide an example where the url is updated when a page is pushed? I am interested in seeing an example with data segments, as well.

Continuing the discussion from How to configure deeplinks in AppModule.forRoot()?:

Thanks,

Denis


#3

I solved this by not using DeepLinker and using ng2 Routers. Seems to be working just fine. Thanks!


#4

Do you have documentation on how to leverage the ng2 Router?


#5

@alexthebuilder, This SO article was the most helpful with what I was trying to do: http://stackoverflow.com/questions/38131293/angular-2-router-navigate.

I wanted to avoid having to deal with router children, so I was able to keep my routing structure mostly the same as what I used on ionic2 beta 6. Notable changes include ‘name’ attribute no longer being used and route params passed as an array instead of a dictionary.

I also had to use a <router-outlet> element in the app.component.html template.

As for bootstrapping the route configuration; see below:

import {Injectable} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';

@Injectable()
export class RouteConfigurator{
    constructor() { }

    static get routeConfig(): Routes {
        return [your routes]
    }
}

export const APP_ROUTES_PROVIDER = RouterModule.forRoot(RouteConfigurator.routeConfig(), {useHash: false});

In app.module.ts, import the APP_ROUTES_PROVIDER and add it to the @NgModule imports collection, like below:

@NgModule({
    declarations: [
        MyApp,
    ],
    imports: [
        APP_ROUTES_PROVIDER,
        IonicModule.forRoot(MyApp)
    ],
    bootstrap: [IonicApp],
    entryComponents: [
        MyApp
    ],
    providers: [
        {provide: APP_BASE_HREF, useValue: "/m"},
        {provide: LocationStrategy, useClass: PathLocationStrategy}
    ]
})
export class AppModule {}

Given all this, the nav stack doesn’t appear to be updated with the pages since they aren’t being pushed onto it (in beta 6, this wasn’t the case, pages were pushed onto the nav stack even though I was using the router).

Hope this helps.

Thanks,
D


How to configure deeplinks in AppModule.forRoot()?
#6

Thanks for this! Sorry its taken me so long to reply! Have you played with using lazy loading or anything of that nature with this setup?


#7

Playing with this right now and it looks like the deeplinker is causing issues. Have you run into this?


#8

Hi @dzincolorado, I read your post. And I’m not sure if I understand it well.
You was able to include @angular/router and configure classical angular2 router, using also main component?
right?

I included @angular/router in version 3.0.0 and tried to implement it, something works and something doesn’t work.

Can you please share a very basic full example for this files: router configure, app.module.ts, app.html and default page
After implementing angular router in ionic, does the ionic-menu still work?

If you can do this it would a very big help for us! thx you very much!!!


#9

Hi @alexthebuilder where you able to implement regular angular router? I asked to @dzincolorado for code sample.


#10

Hey @mburger81,

Sorry, just saw this now. Using ionic-angular 2.0.0-rc.2 with @angular/router 3.1.2 and the remaining @angular packages on 2.1.1; below is an example of app.routes.ts:

import {ModuleWithProviders} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';

export const APP_ROUTES_PROVIDER: ModuleWithProviders = RouterModule.forRoot(
[
{
  path: "",
  component: HomePage,
},
{
  path: "news",
  component: NewsPage,
}
] , {useHash: false});

Below is an example for app.module.ts:

import 'rxjs/Rx';

import { NgModule} from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {HttpModule} from '@angular/http';
import {LocationStrategy, PathLocationStrategy, APP_BASE_HREF} from '@angular/common';
import {FormsModule} from '@angular/forms'

import {APP_ROUTES_PROVIDER} from "./app.routes";
import { IonicApp, IonicModule } from 'ionic-angular';
import { OurApp } from './app.component';

@NgModule({
    declarations: [
        OurApp,
        COMPONENT_DIRECTIVES,
        PAGES
    ],
    imports: [
        APP_ROUTES_PROVIDER,
        BrowserModule,
        FormsModule,
        HttpModule,
        IonicModule.forRoot(OurApp)
    ],
    bootstrap: [IonicApp],
    entryComponents: [
        OurApp,
        PAGES
    ],
    providers: [
        COMMON_PROVIDERS,
        {provide: APP_BASE_HREF, useValue: "/m"},
        {provide: LocationStrategy, useClass: PathLocationStrategy}
    ]
})
export class AppModule {}

our index.html looks like this:

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <!--<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' use.typekit.net 'unsafe-inline'; script-src 'self' use.typekit.net font-src 'self' data: use.typekit.net img-src 'self' p.typekit.net 'unsafe-inline' 'unsafe-eval'">-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">

    <meta name="apple-mobile-web-app-title" content="Our App">
    <meta name="application-name" content="Our App">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="assets/images/raster/favicon/mstile-144x144.png?v=zXXQE6wmrr">
    <meta name="msapplication-config" content="assets/images/raster/favicon/browserconfig.xml?v=zXXQE6wmrr">
    <meta name="theme-color" content="#ffffff">
    <meta name="apple-mobile-web-app-capable" content="yes" />

    <title>title</title>

    <link href="build/main.css" rel="stylesheet">
    <link href="assets/images/sprites/view/sprite.css" rel="stylesheet">

    <base href="/m">

</head>

<body>


    <!-- this Ionic's root component and where the app will load -->
    <ion-app></ion-app>

    <script src="build/polyfills.js"></script>
    <!-- the bundle which is built from the app's source code -->
    <script src="build/main.js"></script>

</body>

</html>

And finally our app.component.html looks like this:

<a [routerLink]="['/']"></a>
<router-outlet></router-outlet>

<bottom-nav></bottom-nav>

The bottom-nav element is our own version of tabs and not ionic’s tabs. We ran into a pretty big issue with using any ionic navigation elements while trying to use ng2 router. Doing this meant we had to write our own logic to track navigation history.

As far as lazy loading, it’s on my list to implement for the next phase of our project. Based on a quick review of the Route interface, looks like the loadChildren callback might be the way to go.

Finally, we don’t currently bundle our code into app/play store package. So, we don’t use any cordova/ionic-native plugins. This is something we might do in the future, though.

Hope this helps.

Denis


New Angular2 Router support in Ionic
#11

Hi @dzincolorado, thx a lot for helping us!!!

Now we are out of office, I will try this tomorrow, the first thing I will do!!!

I have some other questions:
If you do not bundle a build for android or ios, why do you use ionic2? Do you use it for ionic-components?
So you don’t use and you don’t use or ? Right?

Can I ask you on which project do you work?


#12

Hey @mburger81,

I tried bundling when we were on Beta 6 and ran into too many issues to make it worthwhile for us. We were already dealing with moving to two beta frameworks (Ionic 2 and ng2) so that’s not something we wanted to take on as well. I am still interested in bundling and will revisit when/if we see a need for it.

it looks like you had another question about something we’re not using, but the message was cleansed, so it didn’t come through.

Thanks,

Denis


Using Ionic 2 as a browser based web application vis-à-vis --no-cordova not recommended?
#13

hi dzincolorado, we ran into the same issue and will to write our own bottom-nav exactly like yours. Could you please share your effort? thanks.


#14

Hi @angelochen can you also share your code or example how do you using now angular router in inioc2?

Hi also to @dzincolorado
we have a semi working solution, we can load the router can rediriect to default page and are also able to navigate trough this.router.navigate, but after live reload or on navigate trought direct urls in browser (which is the same thing) we run into this error. Do you have some ideas?

We were able to get work a header tootlbar with dynamical content at the rest of the page. But we also where not able to get work bottom header, but that’s not a problem because we doesn’t need one. But if you can share yours we will also be happy. thx


#15

Hey @mburger81 and @angelochen ,

Looks like you need a server running to have all routes point to index.html. Once you have that, and the html is served up, angular2/ionic2 will take over and route to the correct component. In this case, I’m using an expressjs server. Then in bash I just run forever ./dev-server.js --watch --watchDirectory www. Let me know if this works for you.

Below is my dev-server.js:

var express = require('express'),
    app = express(),
    _ = require('lodash'),
    util = require('util'),
    os = require('os'),
    cors = require('cors');


var rootDir = __dirname + '/www',
    port = 3002;


app.use(cors());

app.use(express.static(rootDir));

//app.get('/*', function(req, res){
//  res.sendFile(rootDir + '/index.html');
//});

app.listen(port);


//===================
console.log('Serving files from: ' + rootDir);
console.log('Listening on: ' + getAddresses() + ':' + port + '');
console.log('Press Ctrl + C to stop.');


function getAddresses() {
    var interfaces = os.networkInterfaces(),
        addresses = [];

    _.each(interfaces, function(net) {
        _.each(net, function(address) {
            if (address.family == 'IPv4' && !address.internal) addresses.push(address.address);
        })
    });

    return addresses;
}

#16

@angelochen ,

Below is a snippet from bottom-nav.html. goToHome() essentially calls router.navigate(['/home']). The !! before the method call is the equivalent of vanilla html <a href="javascript:;">, we’re using it here to prevent ng2 xss warnings from appearing.

<div class="tab-wrapper" tappable>
    <a (click)="!!goToHome()">
        <div class="tabbar-icon-alignment">
            <div class="home-icon icon"></div>
        </div>
        <span class="tab-text">Home</span>
    </a>
</div>

I hope this helps.

Denis


#17

Hi, @dzincolorado thx for your answer!

We install our app on android and ios device so we can not put before a web server. Also our webapp is deployed on a embeded hardware which has not so many performance so we need a other solution.

If i understand you, you have the same problem as we and the only solution you have found is this? right?


#18

Hi @mburger81,

I forgot you’re bundling your html/js into the app. Out of curiosity, is this a hard requirement for you? We currently aren’t which is why the router solution works for us.

This SO article might be helpful to you:

Denis


#19

That shouldn’t be an issue unless you are lazy loading routes though. If you are packaging this into one main.js file and your routes point to components I don’t see why your app should not work.


#20

@alexthebuilder, good call, haven’t tried it myself. @mburger81, can you confirm this is the case?
Thanks!

Denis


#21

Hi @dzincolorado & @alexthebuilder, I still have the same problems and I was not able to resolve it.

I created the simplest ionic2 app with rc.3 which is using angular 2.1.1 and integrate the angular router in version 3.1.2.
You can find the code in my public github repo
https://github.com/mburger81/ionic2-angular2-router

This has an app.router.ts where I declare my classical angular2 routes, with three pages: page1, page2 and page3.

If you go to http://localhost:8001 the router is redirecting you to /page1 which is working, the result you can see is this:

On top you have the menu where you can navigate to Home(’/) which is redirecting to /page1, there are also Page1 (/page1), Page2 (/page2) and Page3 (/page3). If you click to the menu buttons the right page will be rendered in the router-outlet, this is working all as expected.

But if you reload the page with F5 or you go directly to the page for example by typing http://localhost:8100/m/page3 you will get this error:

Can you please download my sample app from github, with it you can reproduce the error and help me found a solution??? It will be great for all of us! If you have further questions, please let me know.

thx