简体   繁体   English

Angular 6 QueryParams 不可用 OnInit?

[英]Angular 6 QueryParams Not available OnInit?

Okay so I am creating a simple page which i want the user to pass in a bunch of parameters via the URL.好的,所以我正在创建一个简单的页面,我希望用户通过 URL 传入一堆参数。 The very basic example I have been using is http://localhost:4200/?client_id=test我一直在使用的非常基本的例子是http://localhost:4200/?client_id=test

I am following all the procedures I can find on the internet but for some reason the parameters aren't available OnInit, and are only available via subscription?我正在遵循我可以在互联网上找到的所有程序,但由于某种原因,参数在 OnInit 中不可用,并且只能通过订阅获得?

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  title = 'Login';
  submitted: boolean = false;

  constructor(
    private route: ActivatedRoute){
  }

  ngOnInit(){
    console.log(this.route.snapshot.queryParams); //line 26
    this.route.queryParamMap.subscribe(params => {
      console.log(this.route.snapshot.queryParams); //line 28
    })
  }
}

this is what prints这就是印刷品

{} - line 26
{} - line 28
{client_id: "test"} - line 28

Its as if Angular isn't recognizing the query string parameters until after the page loads?好像 Angular 直到页面加载后才识别查询字符串参数? How can i get around this?我怎样才能解决这个问题?

Edit:编辑:

Ive tried using params.get() also - same result我也试过使用 params.get() - 结果相同

this.route.queryParamMap.subscribe(params => {
  console.log(params.get('client_id'));
})

prints印刷

null
test

so the first activation of the subscription the value is null - then the value changes to test and its updated.所以订阅的第一次激活值为空 - 然后值更改为 test 并更新。 I'm trying to avoid the first "null" value.我试图避免第一个“空”值。

try this :尝试这个 :

this.route.params.subscribe((params:Params) => {
    ... use params['key'] to access its value
});

in my opinion, the best approach is to use subscription and do like this :在我看来,最好的方法是使用订阅并这样做:

在此处输入图片说明

and try this one ...试试这个...

@Component(/* ... */)
export class UserComponent implements OnInit {
    id$: Observable<string>;
    id: string;

    constructor(private route: ActivateRoute) {}

    ngOnInit() {
        this.id$ = this.route.paramMap.pipe(map(paramMap => paramMap.get('id')));

        // or for sync ( one time ) retrieval of id

        this.id = this.route.snapshot.paramMap.get('id');
    }
}

both of these solutions are working if I try it:如果我尝试,这两种解决方案都有效:

 ngOnInit(){
    this.route.queryParamMap.subscribe(params =>
        console.log(params.get("client_id"))
     );

    this.route.queryParams.subscribe(params =>
        console.log(params["client_id"])
    );
 }

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

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