简体   繁体   中英

Angular2 : How to pass value through a form to another component

I'm new to Angular2 and i would like to do something simple :

  1. Submit a form to make an order.
  2. Save the order via an external API into database
  3. Go to the payment page while keeping the order object

My first question : After saving how can I pass object to the other page ?

My second question : Am i even doing this whole "form thing" in the best way ?

form.html

<form [formGroup]="orderForm" #formDir="ngForm" (ngSubmit)="submitForm(formDir.value)">
    [...]
</form>

form.component

submitForm(): void {
    this.orderService.saveOrder(this.order)
        .then(() => this.router.navigateByUrl('/payment', ['order', this.order]));
}

paymentComponent

order: Order;

constructor(route: ActivatedRoute) {
    route.queryParams.subscribe(params => {
        this.order = params['order'];
    });
}

After saving how can I pass object to the other page ?

After form save operation completes, return a current saved order object from API and then while redirecting pass order.id which has been saved in DB. Also make sure you have order parameter mention in the route parameter of route definition.

submitForm(): void {
    this.orderService.saveOrder(this.order)
        .then((savedOrderObj) => this.router.navigateByUrl('/payment', ['order', savedOrderObj.id]));
}

Am i even doing this whole "form thing" in the best way ?

Yes, it seems correct. While navigating to route you're passing order (id) parameter. So the paymentComponent component can retrieve that Order based on order parameter passed to the route.

You should consider moving routeParams subscription code to ngOnInit hook, as constructor shouldn't have any startup logic. Create a OrderService which would be thoroughly responsible for retrieving order data. It can have different method, one of them could be retrieving data based on id.

constructor(private route: ActivatedRoute, private orderService: OrderService) {
}
ngOnInit() {
    this.route.queryParams.subscribe(params => {
        this.orderService.getOrderById(params['order']).subscribe(
           (order) => this.order = order
        );
    });
}

@omeralper's comment is correct you need to use a service to pass complex data types like an object literal, or any data that you don't want to be displayed in the URL, which is what happens with params.

Data Service

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

@Injectable() 
export class DataService {
  data: {[key: string]: any}; 
}

Component X

import {Component} from '@angular/core'

import { DataService } from './data.service';

@Component() 
export class X {

  get data(): {[key: string]: any}{ 
    return this.dataService.data; 
  }

  set data(value: {[key: string]: any}) { 
    this.dataService.data = value; 
  } 

  constructor(public dataService: DataService) { } 

  submitForm(): void {
    this.dataService.set(this.order); // Store order for use by next component
    this.orderService.saveOrder(this.order)
      .then(() => this.router.navigateByUrl('/y'));
  }
}

Component Y

import {Component} from '@angular/core'

import { DataService } from './data.service';

@Component() 
export class Y { 

  data: { [key: string]: any };

  get data(): {[key: string]: any}{ 
    return this.dataService.data; 
  } 

  set data(value: {[key: string]: any}) { 
    this.dataService.data = value; 
  } 

  constructor(public dataService: DataService) { }

  ngOnInit() {
    this.data = this.dataService.get(); // Route component loads and you retrieve the data
  }
}

You'll want to beef up the service, and maybe call it RouteDataService , but this will allow for inter-component communications.

You don't want to make another request if you already have the data available. Doing it once or twice doesn't hurt, but as your application grows making this your strategy will degrade performance.

Otherwise, I prefer reactive forms over template driven forms to keep the logic in the controller and the complexity of the template down, but you're not doing anything wrong that's just a preference. If you haven't checked out reactive forms yet this is a decent intro tutorial for you to compare both.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM