Angular 2可以通过路由参数传递对象吗?

2024-05-18

我可以使用一些建议来解决我面临的这个问题。为了尽可能地向您解释这一点,我创建了一个主要组件:

@Component({
selector: 'main-component',
providers: [...FORM_PROVIDERS, MainService, MainQuoteComponent],
directives: [...ROUTER_DIRECTIVES, CORE_DIRECTIVES, RouterOutlet, MainQuoteComponent ],
styles: [`
    agent {
        display: block;
    }
`],
pipes: [],
template: `
   **Html hidden**
  `,
  bindings: [MainService],
})

@RouteConfig([
    { path: '/', name: 'Main', component: MainMenuComponent, useAsDefault: true },
    { path: '/passenger', name: 'Passenger', component: PassengerComponent },
])

@Injectable()
export class MainComponent {

bookingNumber: string;
reservation: Reservation;
profile: any;

constructor(params: RouteParams, public mainService: MainService) {

    this.bookingNumber = params.get("id");

     this.mainService.getReservation(this.bookingNumber).subscribe((reservation) => {

        this.reservation = reservation;
    });

    this.profile = this.mainService.getUserDetails();

} 

}

该组件从 api 检索预订并将其保存在您看到的预订对象中(它有一种 Reservation 类型,它是一个如下所示的类)

export class Reservation {

constructor(
    public Id: number,
    public BookingNumber: string,
    public OutboundDate: Date,
    public ReturnDate: Date,
    public Route: string,
    public ReturnRoute: string,
    public Passengers: string,
    public Pet: string,
    public VehicleType: string,
    public PassengersList: Array<Passengers>

) { }
}

当我单击“乘客”按钮时,它将重定向到乘客页面“主/乘客”,但这里我需要发送预订对象(整个)或仅发送乘客列表(数组)。

有谁知道是否可以使用路由参数或路由器出口来做到这一点?有什么建议么?


只需使用共享服务并将其添加到providers: [...]父组件的。

简单服务类

@Injectable()
export class ReservationService {
  reservation:Reservation;
}

在父级中将其添加到提供者并将其注入到构造函数中

@Component({...
   providers: [ReservationService]
export class Parent {
  constructor(private reservationService:ReservationService) {}

  someFunction() {
    reservationService.reservation = someValue;
  }
}

在子组件中仅注入它(不要添加到提供程序)

@Component({...
  providers: []
export class Passenger {
  constructor(private reservationService:ReservationService) {
    console.log(reservationService.reservation);
  }

  someFunction() { 
    reservationService.reservation = someValue;
  }
}

update

bootstrap()是一切事物的共同祖先,也是一个有效的选项。这取决于您的具体要求。如果您在组件中提供它,则该组件将成为共享单个实例的树的根。通过这种方式,您可以指定服务的范围。如果范围应该是“您的整个应用程序”,那么将其提供在bootstrap()或根组件。 Angular2 风格指南鼓励偏爱providers根组件的bootstrap()。但结果是一样的。如果你只想在组件之间进行通信A以及添加到其的其他组件<router-outlet>那么限制这个组件的范围是有意义的A.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 2可以通过路由参数传递对象吗? 的相关文章

随机推荐