如何在Angular中处理较大的URL参数

时间:2020-07-21 16:00:32

标签: angular angular8 angular-routing query-parameters

在我的酒店预订应用程序中,该应用程序包含多个阶段,例如酒店搜索->选择酒店->选择房间->付款,并且每个阶段都有不同的页面。所有阶段都期望来自上一阶段的许多输入(在某些情况下约为5-8),例如会话ID,签入,签出等。我正在使用查询参数进行应用内导航,因为当用户刷新页面时,页面不会中断。

我面临的问题是,太多的字段使URL很难看,而且由于URL较大,nginx在某个阶段还会引发错误。我曾尝试将这些数据存储在服务中,但这无济于事,因为刷新页面时,数据会丢失并且无法存储在localStorage中。那么,为了避免这些问题,我在这里可以采取什么正确或最佳方法呢?

1 个答案:

答案 0 :(得分:1)

我会在您的域中引入一个名为BookingDraft之类的实体,您在该实体中进行预订,但这还不是功能齐全的预订。

此实体应具有其自己的唯一ID,该ID将出现在URL中。如果要将草稿实体保留到数据库中,还应该在上面带有用户ID。

export interface BookingDraft {
  // Unique identifier for this draft, such as a GUID. Can be persisted to a database, API, or to localStorage. This should go in the URL.
  id:string;
  userId:string;
  hotelId?:string;
  roomId?:string;
  checkIn?:Date;
  checkOut?:Date;
  sessionId?:string;
}

然后,您的路线中将包含预订ID,然后是该步骤的分段。

/create-booking/{bookingDraftId}/select-hotel
/create-booking/{bookingDraftId}/select-room
/create-booking/{bookingDraftId}/payment

您可以在每个路段的路线上添加保护措施或某种验证逻辑,以确保在用户尝试选择房间之前草稿已经具有hotelId

const routes: Routes = [
  {
    path: 'create-booking/:bookingDraftId',
    children: [
      {
        path: 'select-hotel',
        component: SelectHotelPageComponent
      },
      {
        path: 'select-room',
        component: SelectRoomPageComponent,
        canActivate: [HotelSelectedGuard]
      },
    ]
  }
]

export class HotelSelectedGuard implements CanActivate {
  constructor(private bookingDraftService: BookingDraftService, private router: Router) {}

  public canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean|UrlTree> {
    const draftId = next.paramMap.get('bookingDraftId');

    return this.bookingDraftService
      .getDraft(draftId)
      .pipe(map(draft => {
        if(!!draft.hotelId) {
          return true;
        }

        return this.router.createUrlTree(['create-booking',draftId,'select-hotel'], {
          queryParams: {
            message: 'Please select a hotel before selecting a room'
          }
        })
      }))
  }
}

创建一个BookingDraftService,以与localStorage或某些API之间来回保存预订草稿。