【问题标题】:Angular 6 QueryParams Not available OnInit?Angular 6 QueryParams OnInit 不可用?
【发布时间】:2020-02-25 21:20:18
【问题描述】:

好的,我正在创建一个简单的页面,我希望用户通过 URL 传递一堆参数。我一直在使用的非常基本的例子是http://localhost:4200/?client_id=test

我正在遵循我可以在互联网上找到的所有程序,但由于某种原因,参数在 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
    })
  }
}

这是打印出来的

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

好像 Angular 直到页面加载后才识别查询字符串参数?我该如何解决这个问题?

编辑:

我也尝试过使用 params.get() - 结果相同

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

打印

null
test

所以订阅的第一次激活值为空 - 然后值更改为测试并更新。我试图避免第一个“空”值。

【问题讨论】:

标签: angular angular-activatedroute


【解决方案1】:

试试这个:

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

在我看来,最好的方法是使用订阅并这样做:

【讨论】:

  • 我也试过这个 - 仍然给出一个空值,然后是正确的值。我已经更新了我的问题。
【解决方案2】:

如果我尝试一下,这两种解决方案都可以工作:

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

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

【讨论】:

    【解决方案3】:

    试试这个……

    @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');
        }
    }
    

    【讨论】:

    • 请以文字形式发布,以便于提取。
    猜你喜欢
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    相关资源
    最近更新 更多