Discover the secret to accessing the complete object with navParams in Ionic 3 and Angular 4

At the moment, I am transferring a data object from one page to another (within a Modal).

I need to pass 8 parameters to the modal view.

this.firstParam = navParams.get("firstPassed");
this.secondParam = navParams.get("secondPassed");
.
.
.
this.eightParam = navParams.get("eightPassed");

Is there a way to retrieve the entire object data with just one call?

this.data = navParams.getAll(); //something along these lines

I have looked through the documentation but couldn't find a method for fetching the complete object data.

Answer №1

There's a better way to handle this situation. Instead of sending each piece individually, you can send all the data at once using the method below.

Note: Create a data transfer object named DtoMy

Dto-my.ts

export class DtoMy {
    firstPassed: string;
    secondPassed: string;

    //add any other properties here
}

Sending the Data

let dtoMy = new DtoMy();
dtoMy.firstPassed= 'firstPassed';
dtoMy.secondPassed= 'secondPassed';
//set values for any other properties

const myModal = this.modalCtrl.create('MyModalPage', { data: dtoMy });
myModal.onDidDismiss(data => { });
myModal.present();

Receiving the Data:

my-modal-page.ts

data :DtoMy;

constructor(private navParams: NavParams, private modalCtrl: ModalController) {
      this.data = this.navParams.get('data');
  }

Answer №2

If you want to pass an entire object to the second page, follow these steps:

For sending:

constructor(public navCtrl: NavController, public navParams : NavParams){}

 public userObject = 
 {
  firstName : "john",
  lastName  : "smith"
 }

clickMe()
{
  this.navCtrl.push(SecondPage,this.userObject);
}

You need to import both NavController and NavParams, then use the push() method to navigate to the second page with the desired object.

In the second Page:

export class SecondPage 
{

 userObject;
 userName;

 constructor(public navCtrl: NavController, public navParams: NavParams){}

  ngOnInit()
  {
  this.userObject = this.navParams.data;
  this.userName   = this.userObject.firstName;
  console.log(this.userObject);
  }
}

To access the object in the second page, use the data member of NavParams. If you need to access the lastName, simply do

this.lastName=this.userObject.lastName

Answer №3

function initiatePage(nav: NavController, params: NavParams) {
console.log(params.data)
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Seeking out a particular key within a JSON object and then finding a match based on the id within that key's array - how can it be

Recently, I've been exploring JavaScript and encountering challenges when trying to apply array methods on objects. For instance, I received a fetch response and my goal is to extract the 'entries' key and then utilize the native Array.find( ...

Error with Angular 5 Cross-Origin Resource Sharing

I am new to Angular development and here is the code I have written: export class FaceProfilComponent implements OnInit { domparser = new DOMParser(); doc: HTMLDocument; element: any; constructor(private http: HttpClient) {} get ...

Challenges with Loading JSON Dynamically in Next.js using an NPM Package

In my TypeScript project, I have implemented a functionality where a json configuration file is dynamically loaded based on an enum value passed as a parameter to the getInstance function in my PlatformConfigurationFactory file. public static async getIn ...

Creating a UniqueAsynValidator in Angular Reactive Forms 2

I'm having trouble implementing an Async Validator in my Reactive forms and I keep encountering errors. Any help would be greatly appreciated. Custom Validator Code import { AbstractControl } from '@angular/forms'; import { Observable } fr ...

An example in Typescript for setting an initial/default value for a data type

Can you create a Type with a default value included? For example: type Animal = { kind : "animal" Legs : number, CanFly: boolean } const monkey: Animal = { Legs: 4, CanFly: false}; //In this line, clients must initialize the same value `kin ...

The query parameters and URL are failing to update properly

constructor( private router: Router, private activatedRoute: ActivatedRoute, ) {} ngOnInit() { this.activatedRoute.queryParams.subscribe(params => { //subscribe to param change console.log('params', params) } upd ...

how to send both the useState setter and object as props to a child component in React using TypeScript

Having an issue with passing useState setter and object (both together) to the child component. Successfully passed the object by spreading it like this {...object}, but unsure of the syntax to pass the setter along as well. Here's a code example: < ...

Angular fails to combine values within routerLink

The issue is straightforward - I have a component that retrieves the last searched items saved in sessionStorage as an array of ListItem objects: export class SearchlistComponent { results = JSON.parse(<string>sessionStorage.getItem("lastSear ...

Issue with importing CSS/SASS into Vue Cli 3 Typescript within the <script> block

Recently, I created a new Vue app using TypeScript with Vue Cli 3. However, when attempting to import CSS or Sass into my TypeScript file, I encountered the following issue: import * as sassStyles from '@/assets/sass/my.module.scss'; This re ...

Error: Angular variable is undefined when using template-driven validation

When I create a form using a template-driven approach and submit it, an error occurs stating that all form fields are undefined. The form consists of five fields, and I attempt to clear them using the reset form function. As a novice in Angular, I am uncer ...

The inclusion of individual CSS files in a TypeScript React project does not have any effect

My issue involves creating a new react project with typescript and adding a custom component with a separate CSS file for styling. The folder structure is as follows: https://i.sstatic.net/UNtEP.png In the Header.css file, I have defined a class: .mainHe ...

Is the epoch date format not compatible with the ngx bootstrap datepicker?

Consider this scenario: Jun 13, 2003, 23:11:52.454 UTC represented in epoch date format as 1055545912454. However, when I input this value as bsValue, I receive undefined. Objective My goal is to send the date in epoch format when making a server request ...

issue with the return value of the canActivated guard

In an attempt to secure my main page, I've implemented a guard using the checkTokenValidation() method to verify authentication tokens from users. However, my IDE is flagging an error: "A function whose declared type is neither 'void' nor &a ...

Using TypeScript to encapsulate a Firebase promise

I am in the process of refactoring two functions to make them more concise and efficient: async registerUser(newUser: User) { await this.db.auth .createUserWithEmailAndPassword(newUser.email, newUser.pass) .then(data => { this ...

Confirm the presence of an element in a FormGroup using Typescript

In my FormGroup, which I will refer to as form, I need to set multiple values from an object: Here is the current code snippet: if(form.get('value1') && myObj.val1){ form.get('value1).patchValue(myObj.val1); } if(form.get(' ...

Utilizing Angular 7 in an Apache Server environment to include the Instagram API redirect URL with the useHash set to true

I'm currently having trouble setting up my Angular Application on an Apache Server. The issue I'm encountering involves Instagram authentication. When wanting to allow direct access to a specific Angular page on the Apache server, for example ht ...

Is it recommended to utilize both Ngrx/effect and Angular 2 interceptor?

As I navigate through the redux pattern, it seems to me that ngrx/effect can accomplish similar tasks to Angular interceptors. Currently, I have written some interceptors to include Hawk credentials in all requests. Would migrating this functionality to ...

Customize the Default Functionality in Angular Material Expansion Panel Header

I'm currently attempting to customize the collapse and expand functionality of the Angular Material Expansion Panel. By default, when a user clicks anywhere in the Panel Header, the Expansion Panel will toggle between expanding and collapsing. My go ...

By default, showcase the value of the first item in the list selected in a mat-selection-list on a separate component

In my project, I have two essential components: 1)list (which displays a list of customers) 2)detail (which shows the details of a selected customer) These components are designed to be reusable and are being utilized within another component called cus ...

Production environment experiencing issues with Custom Dashboard functionality for AdminJS

I have successfully integrated AdminJS into my Koa nodejs server and it works perfectly in my local environment. My objective is to override the Dashboard component, which I was able to do without any issues when not running in production mode. However, wh ...