簡體   English   中英

Angular 6 QueryParams 不可用 OnInit?

[英]Angular 6 QueryParams Not available OnInit?

好的,所以我正在創建一個簡單的頁面,我希望用戶通過 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

所以訂閱的第一次激活值為空 - 然后值更改為 test 並更新。 我試圖避免第一個“空”值。

嘗試這個 :

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

在我看來,最好的方法是使用訂閱並這樣做:

在此處輸入圖片說明

試試這個...

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

如果我嘗試,這兩種解決方案都有效:

 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