簡體   English   中英

為什么在應用程序組件中進行服務注入會導致URL參數未定義?

[英]Why does service injection in app component cause undefined for URL parameters?

我有一項服務,可以從URL讀取幾個參數。 在嘗試將服務注入到app.component.tsconstructor中或嘗試從app.component.ts調用服務方法之前,它app.component.ts 然后url參數是未定義的。

知道這可能是什么原因嗎?

my-service.service.ts

...
public param1;
constructor(public router: Router, private http: HttpClient) {
    this.param1 = 
     this.router.parseUrl(this.router.url).queryParams['todo'];
    console.log('param1: ' + this.param1); // returns undefined if the service is injected in app.component
}
....

app.component.ts

...
import { MyService } from './service/my-service.service';
....
constructor(private http: HttpClient, public myService: MyService) {
    ...
}

當我們傳遞一些參數時,我們總是這樣做:

import { Router, ActivatedRoute } from '@angular/router';

  constructor(
    private router: Router,
    private route: ActivatedRoute
  ){ 
      this.route.params.subscribe(params => {
        let todo = params['todo'];
      });
  }

也許您必須將預訂移至ngOnInit(),但通常這應該可行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM