[英]Why does service injection in app component cause undefined for URL parameters?
我有一項服務,可以從URL讀取幾個參數。 在嘗試將服務注入到app.component.ts
的constructor
中或嘗試從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.