我是Angular2的新手,我想做一些简单的事情:
我的第一个问题:保存后如何将对象传递给另一个页面?
我的第二个问题:我是不是以最好的方式做了整个“形式”的事情?
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'];
});
}发布于 2017-10-10 21:10:22
@omeralper的注释是正确的--您需要使用一个服务来传递复杂的数据类型,比如对象文本,或者您不希望在URL中显示的任何数据,这就是params的情况。
数据服务
import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
data: {[key: string]: any};
}组件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'));
}
}组件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
}
}您可能会想要加强服务,也许将其称为RouteDataService,但这将允许组件间通信。
如果您已经拥有可用的数据,则不希望提出另一个请求。做一次或两次并不会有什么影响,但是随着应用程序的发展,您的策略会降低性能。
否则,我更喜欢反应表单而不是模板驱动的表单,以降低控制器中的逻辑和模板的复杂性,但是您没有做任何错误的事情,这只是一种偏好。如果您还没有签出反应性表单,那么这是一个不错的入门教程,您可以对两者进行比较。
https://stackoverflow.com/questions/46675362
复制相似问题