Stark
Stark

Reputation: 481

Passing the sensitive and long data from one component to another in Angular 2

I have a page where user will enter the username, password. Below that there is table where user will select few rows and enter enter data in selected rows.

Page look like this: enter image description here

Now, where user click on next button(which is after table) data will transfer to new page. I have created onClickAction() method

For this i have used routes. I have created Routes.forRoot() and passed data as:

imports: [BrowserModule,
  FormsModule,
   RouterModule.forRoot([
     { path: 'main-page', component: MainPageComponent },
     { path: 'exe/:template', component: ExecutionComponent },
   ])
 ],

what should i put in onClickAction() in order to pass username password url and rows which user has selected?

Also is it correct to pass credentials and such big data in url?

Upvotes: 1

Views: 1539

Answers (1)

Nilmi Nawalage
Nilmi Nawalage

Reputation: 347

If the data is not sensitive and there are only few parameters to be passed, the convenient option to pass data between routes would be to use query parameters(the data will be passed in querystring).

In the component function which triggers the navigation (i.e.: your onClickAction()):

let navigationExtras: NavigationExtras = {
        queryParams: {
            "couldName": this.cloudName,
            "jobName": this.jobName
        }
    };
    this.router.navigate(["page2"], navigationExtras);

In the component where you navigated (i.e.: page2 component):

public constructor(private route: ActivatedRoute) {
    this.route.queryParams.subscribe(params => {
        this.cloudName= params["couldName"];
        this.jobName= params["jobName"];
    });

However, since you have sensitive data like username and password as well as the data you need to pass are complex(not one or two parameters), you can write a provider which is injectable to the components you need.

Provider:

import { Injectable } from '@angular/core';
@Injectable()
export class DataProvider {
    public data: any;
    public constructor() { }
}

In page1 component:

import { DataProvider } from "../../providers/dataProvider";
-------
-------
public constructor(private router: Router, private dataProvider: DataProvider) {}
public onClickAction() {
      this.dataProvider.data= {
         "userName": this.userName,
         "password": this.password,
         "wsdlUrl":this.url,
         ---------
         ---------
         }
       this.router.navigate(["page2"]);
}

In page2 component

import { DataProvider } from "../../providers/dataProvider";
-------
-------
public constructor(private dataProvider: DataProvider) {
        console.log(this.dataProvider.data.userName);
}

Refer this article for more details.

Upvotes: 2

Related Questions