Man*_*sen 24 angular2-routing angular
我可以使用一些建议如何解决我面临的这个问题.为了向您解释这一点,我创建了一个主要组件:
@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();
}
}
Run Code Online (Sandbox Code Playgroud)
该组件从api中检索预订并将其保存在您看到的预订对象中(它有一种预订类型,类似于此类)
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>
) { }
}
Run Code Online (Sandbox Code Playgroud)
当我单击按钮Passenger时,它将重定向到乘客页面Main/passenger,但是这里我需要发送预订对象(整个)或PassengerList(数组).
有没有人知道它是否可以用路由参数或路由器插座来做到这一点?有什么建议?
Gün*_*uer 34
只需使用共享服务并将其添加到providers: [...]父组件即可.
简单的服务类
@Injectable()
export class ReservationService {
reservation:Reservation;
}
Run Code Online (Sandbox Code Playgroud)
在父级中将其添加到提供程序并将其注入构造函数中
@Component({...
providers: [ReservationService]
export class Parent {
constructor(private reservationService:ReservationService) {}
someFunction() {
reservationService.reservation = someValue;
}
}
Run Code Online (Sandbox Code Playgroud)
在子组件中只注入它(不要添加到提供者)
@Component({...
providers: []
export class Passenger {
constructor(private reservationService:ReservationService) {
console.log(reservationService.reservation);
}
someFunction() {
reservationService.reservation = someValue;
}
}
Run Code Online (Sandbox Code Playgroud)
更新
bootstrap()是一切的共同祖先和有效的选择.这取决于您的具体要求.如果在组件上提供它,则此组件将成为共享单个实例的树的根.这样您就可以指定服务的范围.如果范围应该是"您的整个应用程序",则提供它bootstrap()或根组件.Angular2风格指南鼓励支持providers根组件bootstrap().结果将是相同的.如果您只想在组件A和添加到其中的其他组件之间进行通信,<router-outlet>那么将范围限制为此组件是有意义的A.
| 归档时间: |
|
| 查看次数: |
22975 次 |
| 最近记录: |