如何在Angular中从重定向的URL中获取QueryParams?

问题描述 投票:-1回答:3

我有一个特定的网址,在那里我必须重定向用户进行认证,我将得到一个代码作为查询参数。

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

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

angular typescript query-parameters
3个回答
0
投票

重定向路由器到其他路由:我们可以配置路由器默认重定向到一个命名的路由。

    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();
  }
}

0
投票

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

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

-1
投票
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'];
    });
  }
© www.soinside.com 2019 - 2024. All rights reserved.