jueves, 1 de febrero de 2018

How to Use Forms in Angular 2 passing complex data objects between pages

Hi everybody!

Today we are going to explain how to pass form data object like a complex object between pages in Angular 2 or 4 or 5.

First of all, we have to declare our Data object like an injectable, on this way:

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

@Injectable()
export class Data {
    public storage: any;
    public constructor() { }
}

Then, we have to declare our Data object like a provider in our ngModule class file configuration, on this way:

@NgModule({
    declarations: [AppComponent, ...appComponents],
    bootstrap: [AppComponent],
    imports: [
        NativeScriptModule,
        NativeScriptRouterModule,
        NativeScriptRouterModule.forRoot(appRoutes)
    ],
    providers: [Data]
})
class AppComponentModule {}

Then we can use this Data object in our pages.

First of all, we are going to define this in our first page, the origin one:

public constructor(private router: Router, private data: Data) {}

public navigationToPage2() {
   this.data.storage = {
        "firstname": "Nic",
        "lastname": "Raboy",
        "address": {
            "city": "San Francisco",
            "state": "California"
}
   }
   this.router.navigate(["page2"]);
}

And then, we will get the Data object in our second page, which receive the request of our form POST:

public constructor(private data: Data) {
    console.log(JSON.stringify(this.data.storage));
}

Only we need now is to pass our form to the this.data.storage like a JSON file on this way:

this.data.storage = {
    "requestData": JSON.stringify(requestData)
};

And the get the Data on the second page this way:

console.log(this.data.storage.requestData);

I hope you have found it useful and that you have solved your problems.

Try it and have fun!

No hay comentarios:

Publicar un comentario