简体   繁体   English

Angular 7/8 - 如何在应用组件中获取 url 参数

[英]Angular 7/8 - How to get url parameters in app component

I have Single sign on in place but for testing I want to read the values from the url localhost:4200/?id=test&name=testing&email=testing@test.com and pass them to an API in app component.我有单点登录,但为了测试,我想从 url localhost:4200/?id=test&name=testing&email=testing@test.com读取值并将它们传递给应用程序组件中的 API。

there will be a flag on which basis I will reading from url instead of using single sign on function将有一个标志,在此基础上我将从 url 读取而不是使用单点登录功能

if (url_enabled == true) {
    getParamsFromUrl()
 } else {
   singleSignOn()
 }

I tried ActivatedRoute but it doesn't seem to be working.我尝试了 ActivatedRoute,但它似乎不起作用。

I have tried queryParams, params, url, queryParamsMap but none of these seems to be working.我尝试过queryParams, params, url, queryParamsMap但这些似乎都不起作用。 all I get is empty value.我得到的只是空值。

inside app component内部应用组件

app.component.ts app.component.ts

 getParamsFromUrl() {
    this._router.events.subscribe((e) => {
      if (e instanceof NavigationEnd) {
        console.log(e.url)
      }
    })
  }

 this.route.queryParams.subscribe(params => {
      console.log(params);
    })

app.component.html应用程序组件.html

<router-outlet></router-outlet>

app-routing.module.ts app-routing.module.ts

const routes: Routes = [
  {path:'*/:id', component: AppComponent},
];

I have tried whatever I could found on stackoverflow or other blogs.我已经尝试了我可以在 stackoverflow 或其他博客上找到的任何内容。 Can somebody point out what am I missing here?有人可以指出我在这里缺少什么吗?

For this route: You can try this way:对于这条路线:您可以尝试这种方式:

const routes: Routes = [
   {path:'*/:id', component: AppComponent},
];   

In AppComponent .ts file:在 AppComponent .ts 文件中:

    constructor(
      private activatedRoute: ActivatedRoute,
    ) { }




    ngOnInit() {
      this.activatedRoute.params.subscribe(params => {
          const id = params['id'];
          console.log('Url Id: ',id);
    }

    OR

    ngOnInit() {
      this.activatedRoute.queryParams.subscribe(params => {
          const id = +params.id;
          if (id && id > 0) {
           console.log(id);
          }
      });
    }
  
  

first of all there is an url with queryParams like yours :首先,有一个像你这样的带有 queryParams 的 url:

localhost:4200/?id=test&name=testing&email=testing@test.com本地主机:4200/?id=test&name=testing&email=testing@test.com

in this way tou get to the queryparams with ActivatedRoute object lik :通过这种方式,您可以使用 ActivatedRoute 对象获取查询参数,例如:

 this.name = this.activatedRoute.snapshot.queryParamMap.get('name'); // this.name = 'testing'

Or :要么 :

 this.activatedRoute.queryParams.subscribe(params => {
       this.name= params['name'];
     });

and the other way is另一种方式是

localhost:4200/test/testing/testing@test.com本地主机:4200/test/testing/testing@test.com

you use for sync retrieval (one time) :您用于同步检索(一次):

this.name = this.activatedRoute.snapshot.ParamMap.get('name');

Angular comes us with the ActivatedRoute object. Angular 给我们带来了 ActivatedRoute 对象。 We can access the URL parameter value in same way its done above with little difference.我们可以以与上面相同的方式访问 URL 参数值,几乎没有区别。 Data in this type can be accessed with two different ways.这种类型的数据可以通过两种不同的方式访问。 One is through route.snapshot.paramMap and the other is through route.paramMap.subscribe.一种是通过 route.snapshot.paramMap,另一种是通过 route.paramMap.subscribe。 The main difference between the two is that the subscription will continue to update as the parameter changes for that specific route.两者之间的主要区别在于订阅将随着该特定路由的参数更改而继续更新。

ngOnInit() {
    this.route.paramMap.subscribe(params => {
        this.userType = params.get("userType")
    })
}

You need to create a new component and update the routing configuration as follows:您需要创建一个新组件并更新路由配置,如下所示:

First, create a new component: MainComponent :首先,创建一个新组件: MainComponent

import { Component } from '@angular/core';

@Component({
  selector: 'main',
  template: `<router-outlet></router-outlet>`,
})
export class MainComponent {
  constructor() {  }
}

Then, update your AppModule :然后,更新您的AppModule

import { AppComponent } from './app.component';
import { MainComponent } from './main.component';

@NgModule({
  imports:      [ 
    BrowserModule, 
    FormsModule,
    RouterModule.forRoot([
      {path: '', component: AppComponent}
    ])
  ],
  declarations: [ MainComponent, AppComponent ],
  bootstrap:    [ MainComponent ]
})
export class AppModule { }

Finally, you'll need to update your index.html file(Make sure to load the brand new component instead of the AppComponent ):最后,您需要更新index.html文件(确保加载全新的组件而不是AppComponent ):

<main>loading</main>

Now you'll be able to read your parameters as requested in your AppComponent :现在,您将能够按照AppComponent要求读取参数:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  params: Params;

  constructor(private route: ActivatedRoute){}

  ngOnInit() {
      this.route.queryParams.subscribe((params: Params) => {
        this.params = params;
        console.log('App params', params);
        const id = params['id'];
        console.log('id', id);
      });
  }
}

See a working example here: https://read-params-app-component.stackblitz.io/?id=test&name=testing&email=testing@test.com .在此处查看一个工作示例: https : //read-params-app-component.stackblitz.io/?id=test&name=testing&email=testing@test.com

And find the source code here .并在此处找到源代码。

I hope it helps!我希望它有帮助!

You can try like this你可以这样试试

constructor(
  private activatedRoute: ActivatedRoute
)

ngOnInit() {
  this.activatedRoute.paramMap
            .pipe(
               tap(console.log(this.activatedRoute.snapshot.paramMap.get(
                        "id"
                   )))
             ).subscribe()
}

Let me know if you need any help如果您需要任何帮助,请告诉我

Using Transition from @uirouter/core makes it easy to get params from url.使用@uirouter/core Transition可以很容易地从 url 获取参数。

import {Transition} from '@uirouter/core';

@Component()
export class MyComponent {
public myParam = this.transition.params().myParam;

public constructor(public transition: Transition) {}
}

I used jquery inside angular 8 and got the href using jquery $ variable after declaring it in app component.我在 angular 8 中使用了 jquery,并在 app 组件中声明后使用 jquery $ 变量获得了 href。

import { query } from '@angular/animations';

declare var $: any;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM