Ionic 4 & Angular Router – prosljeđivanje parametara

Ionic 4 & Angular Router – prosljeđivanje parametara

Sličan blog post, pod naslovom “Ionic 2 – prosljeđivanje parametara između stranica“, sam već objavio, ali vrijeme je za novi jer Ionic 4 više ne radi isključivo na dosadašnji pop/push način, nego koristi Angular Router, pod uvjetom da se koristi i Angular Framework u pozadini.

Kreiranje projekta

Novi Ionic 4 projekt kreiram već dobro poznatom naredbom:

$ ionic start Ionic4AngularRouter blank
$ cd Ionic4AngularRouter

U ovom koraku trebam postaviti temelj tj. na HomePage komponenti gdje ću kreirati dva gumba kako bi mogao prikazati dva načina za prosljeđivanje parametara.

<ion-header>
  <ion-toolbar color="primary">
    <ion-title>
      Ionic 4 - Angular Router
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>
  <ion-button expand="full" color="dark" (click)="queryParamsFunction()">
    Query Params
  </ion-button>
 
  <ion-button expand="full" color="dark" (click)="navigationExtrasFunction()">
    Navigation Extras
  </ion-button>
</ion-content>

Na ekranu će to izgledati ovako:

Ionic 4 & Angular Router

Osim toga, moram pripremiti i neke podatke, about objekt, koje ću prosljeđivati na sljedeću stranicu.

import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  about = {
    name: 'Tomislav Stanković',
    website: 'www.tomislavstankovic.com',
    interests: [
      'Ionic', 'Angular', 'NodeJS'
    ]
  };

  constructor() {}

  queryParamsFunction(){}

  navigationExtrasFunction(){}

}

Sada mogu kreirati stranicu na koju ću proslijediti podatke i prikazati ih. To činim pomoću naredbe:

$ ionic generate page details

Ionic 4 & Angular Router

Prosljeđeni podaci će na ovom ekranu biti prikazani na sljedeći način:


  
    
      
    
    Angular Router / Details
  

 


  
    
      {{ data.name }}
    
    
        {{ data.website }}
    
  
  
    
      {{ i }}
    
  

Ionic 4 & Angular Router

Sada napokon mogu pokazati kako proslijediti podatke tj. parametre sa HomePage na DetailsPage na dva načina.

Prosljeđenim ću parametrima pristupiti kroz ActivatedRoute.

Query Params

Ovaj način je najčešći s kojim sam se susretao i ok je ako se radi mobilna aplikacija kojoj će se pristupati kroz npr. Google Play Store jer se u tom slučaju neće vidjeti URL svake od stranica.

http://localhost:8101/details?aboutData=%7B%22name%22:%22Tomislav%20Stankovi%C4%87%22,%22website%22:%22www.tomislavstankovic.com%22,%22interests%22:%5B%22Ionic%22,%22Angular%22,%22NodeJS%22%5D%7D

Podatke prosljeđujem sa HomePage

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  about = {
    name: 'Tomislav Stanković',
    website: 'www.tomislavstankovic.com',
    interests: [
      'Ionic', 'Angular', 'NodeJS'
    ]
  };

  constructor(private _router: Router) {}

  queryParamsFunction(){
    this._router.navigate(['/details'], 
       { queryParams: 
           { aboutData: JSON.stringify(this.about) }
       }
    );
  }

  navigationExtrasFunction(){}

}

Na DetailsPage podatke dohvaćam na sljedeći način:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-details',
  templateUrl: './details.page.html',
  styleUrls: ['./details.page.scss'],
})
export class DetailsPage implements OnInit {

  data: any;

  constructor(private _activatedRoute: ActivatedRoute) { 

   this._activatedRoute.queryParams.subscribe(params => {
        if (params && params.aboutData) {
            this.data = JSON.parse(params.aboutData);
            console.log(this.data);
        }
    });  

  }

   ngOnInit() {}

}

U praksi to izgleda ovako:

Ionic 4 & Angular Router

Navigation Extras State

Kako bi ovo funkcioniralo potrebno je koristiti Angular 7.2 ili noviju verziju.

State passed to any navigation. This value will be accessible through the extras object returned from router.getCurrentNavigation() while a navigation is executing. Once a navigation completes, this value will be written to history.state when the location.go or location.replaceState method is called before activating of this route. Note that history.state will not pass an object equality test because the navigationId will be added to the state before being written.

While history.state can accept any type of value, because the router adds the navigationId on each navigation, the state must always be an object. – NavigationExtras

Ovo rješenje je slično onome iznad s tom razlikom što izgleda ljepše kada je vidljiv URL jer se parametri ne vide. To je posebno korisno kada se radi Ionic Progressive Web App.

http://localhost:8101/details

Podatke prosljeđujem sa HomePage

import { Component } from '@angular/core';
import { Router, NavigationExtras } from '@angular/router';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  about = {
    name: 'Tomislav Stanković',
    website: 'www.tomislavstankovic.com',
    interests: [
      'Ionic', 'Angular', 'NodeJS'
    ]
  };

  constructor(private _router: Router) {}

  queryParamsFunction(){}

  navigationExtrasFunction(){
    let navigationExtras: NavigationExtras = {
      state: {
        aboutData: this.about
      }
    };
    this._router.navigate(['/details'], navigationExtras);
  }

}

Na DetailsPage podatke dohvaćam na sljedeći način:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-details',
  templateUrl: './details.page.html',
  styleUrls: ['./details.page.scss'],
})
export class DetailsPage implements OnInit {

  data: any;

  constructor(private _activatedRoute: ActivatedRoute,
              private _router: Router) { 

      this._activatedRoute.queryParams.subscribe(params => {
          if (this._router.getCurrentNavigation().extras.state) {
              this.data = this._router.getCurrentNavigation().extras.state.aboutData;
              console.log(this.data);
          }
      });

  }

   ngOnInit() {
  }

}

U praksi to izgleda ovako:

Ionic 4 & Angular Router

Zaključak

Struktura projekta prema package.json

{
  "name": "Ionic4AngularRouter",
  "version": "0.0.1",
  "author": "Tomislav Stanković",
  "homepage": "https://www.tomislavstankovic.com/",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^7.2.2",
    "@angular/core": "^7.2.2",
    "@angular/forms": "^7.2.2",
    "@angular/http": "^7.2.2",
    "@angular/platform-browser": "^7.2.2",
    "@angular/platform-browser-dynamic": "^7.2.2",
    "@angular/router": "^7.2.2",
    "@ionic-native/core": "^5.0.0",
    "@ionic-native/splash-screen": "^5.0.0",
    "@ionic-native/status-bar": "^5.0.0",
    "@ionic/angular": "^4.1.0",
    "core-js": "^2.5.4",
    "rxjs": "~6.5.1",
    "tslib": "^1.9.0",
    "zone.js": "~0.8.29"
  },
  "devDependencies": {
    "@angular-devkit/architect": "~0.13.8",
    "@angular-devkit/build-angular": "~0.13.8",
    "@angular-devkit/core": "~7.3.8",
    "@angular-devkit/schematics": "~7.3.8",
    "@angular/cli": "~7.3.8",
    "@angular/compiler": "~7.2.2",
    "@angular/compiler-cli": "~7.2.2",
    "@angular/language-service": "~7.2.2",
    "@ionic/angular-toolkit": "~1.5.1",
    "@types/node": "~12.0.0",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "~4.5.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "ts-node": "~8.1.0",
    "tslint": "~5.16.0",
    "typescript": "~3.1.6"
  },
  "description": "An Ionic project"
}

Objavio

Tomislav Stanković

Bloger širokog raspona interesa od kojih dio voli objaviti na ovom blogu. U neslobodno vrijeme Angular developer mobilnih i web aplikacija.

Odgovori

Vaša adresa e-pošte neće biti objavljena. Obavezna polja su označena sa *