首页 > 解决方案 > 读取路线参数 Angular

问题描述

我正在使用 Paypal API,在确认购买后,它会重定向到您想要的 url,我将希望的 url 设置为“localhost:4200/shop/order”。但是,每当贝宝返回 url 时,他们会在结尾 url “localhost:4200/shop/order?token=8YS089366D9655&PayerID=ASDVD4BLMH”添加令牌和 payerid,但是当它回到我的角度应用程序时,我有一个错误说找不到页面。

我尝试了几种配置路由的方法,但所有尝试都失败了。如果Angular不接受“?” 和路线中的“&”。

const shopRoutingConfig:Routes = [
    {
        path:'',component:ShopAppComponent,
        children:[
            {path:'purchase',component:PurchaseComponent},
            {
                path:'order/:token/:payerid', //fail in url returned from paypal
                component:OrderComponent
            }
        ]
    }
]

@NgModule({

    imports:[
        RouterModule.forChild(shopRoutingConfig)
    ],
    exports:[RouterModule],

})
export class ShopRoutingModule{}

我的订单组件:

export class OrderComponent implements OnInit
{

    constructor(private route:ActivatedRoute) {
    }

    ngOnInit(): void {
        debugger
       const routeParams = this.route.snapshot.paramMap;
       var tokenText = routeParams.get('token')
       var userId = routeParams.get('PayerID')
    }
}

唯一可行的方法是,如果我手动将 url 编辑为“localhost:4200/shop/order/8DC695025P9917207”

标签: javascriptangular

解决方案


"localhost:4200/shop/order?token=8YS089366D9655&PayerID=ASDVD4BLMH" token 和 PayerId 是查询参数,但是你已经将你的路由描述为 order/:token/:payerId,也就是路由参数。因此,如果重定向 URL 为“localhost:4200/shop/order/8YS089366D9655/ASDVD4BLMH”,它就会起作用。

由于重定向 URL 使用 queryParams 返回,因此最好将您的路由设置为

path:'order/', component: yourComponent

并在 component.ts

  constructor() {
  this.route.queryParams.subscribe(params => {
   this.tokenText = params.token:
   this.userId = params.payerId
  })
}

推荐阅读