【问题标题】:How to get QueryParams from redirected URL in Angular如何从 Angular 中的重定向 URL 获取 QueryParams
【发布时间】:2020-05-19 12:03:25
【问题描述】:

我有一个特定的 url,我必须重定向用户进行身份验证,我会得到一个代码作为查询参数。

假设我将用户重定向到http://someurl.com,它将被重定向到另一个网址,我将获取代码作为查询参数,例如http://anotherurl.com?code=1234

所以我使用window.location.href="http://someurl.com" 来重定向用户 但是如何在 Angular 中获取此代码?

【问题讨论】:

  • 你提到了这个这些网址不是我的角度应用程序或角度组件的一部分。这些是不同的 url 好几次,那么您在 Angular 应用程序中的起点在哪里,您将用户重定向到外部 URL ?是这样的场景吗?
  • 起始部分是http://myApplication.com/SomePage,我必须将用户重定向到http://authurl.com/?access_url=http://myApplication.com,然后它会将我重定向到http://myApplication.com?code=1234。它会将代码作为查询参数发送给我
  • 当重定向到您的应用程序http://myApplication.com?code=1234 时,您可以简单地使用:private code: number; ngOnInit(): void { this.route.queryParamMap.subscribe((queryParams: ParamMap) => { this.code = Number.parseInt(queryParams.get('code')); }); }

标签: angular typescript query-parameters


【解决方案1】:

将路由器重定向到另一个路由: 我们可以将路由器配置为默认重定向到命名路由:

    export const routes: Routes = [
  { path: '', redirectTo: 'component-one', pathMatch: 'full' },
  { path: 'component-one', component: ComponentOne },
  { path: 'component-two', component: ComponentTwo }
];

读取路由参数:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'product-details',
  template: `
    <div>
      Showing product details for product: {{id}}
    </div>
  `,
})
export class LoanDetailsPage implements OnInit, OnDestroy {
  id: number;
  private sub: any;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       this.id = +params['id']; // (+) converts string 'id' to a number

       // In a real app: dispatch action to load the details here.
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}

【讨论】:

  • 这些 url 不是我的 Angular 应用程序或 Angular 组件的一部分。这些是不同的网址
【解决方案2】:
in Routing file define routes like below
const routes: Routes = [
  {path: 'planner', component: PlannerTrackerComponent },
  {path: '' ,  component: PlannerTrackerComponent },
  {path: 'planner/:id' , component: PlannerTrackerComponent}
];

in Ts file :
 constructor(private activeRoute: ActivatedRoute) { }
 ngOnInit() {
    this.activeRoute.queryParams.subscribe(params => {
      this.id = params['id'];
    });
  }

【讨论】:

  • 这些 url 不是我的 Angular 应用程序或 Angular 组件的一部分。这些是不同的网址
  • 显然这些只是举例,你可以给你 url,我刚刚展示了如何从 url 获取 id
【解决方案3】:

使用 ActivatedRoute 你可以得到这样的查询参数

code: string;
constructor(private route: ActivatedRoute) {
   console.log('Called Constructor');
    this.route.queryParams.subscribe(params => {
        this.code = params['code'];
    });
}

【讨论】:

猜你喜欢
  • 2019-02-09
  • 2021-11-09
  • 2016-12-11
  • 1970-01-01
  • 2013-02-24
  • 1970-01-01
  • 2011-03-22
  • 2018-05-02
  • 1970-01-01
相关资源
最近更新 更多