[英]Why does service injection in app component cause undefined for URL parameters?
I have a service where I read couple of parameters from the URL. 我有一项服务,可以从URL读取几个参数。 looks good till I try to inject the service in the
constructor
of the app.component.ts
or I try to call a service method from the app.component.ts
. 在尝试将服务注入到
app.component.ts
的constructor
中或尝试从app.component.ts
调用服务方法之前,它app.component.ts
。 Then the url-parameters are undefined. 然后url参数是未定义的。
Any idea what could be the reason for that? 知道这可能是什么原因吗?
my-service.service.ts
: 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
: app.component.ts
:
...
import { MyService } from './service/my-service.service';
....
constructor(private http: HttpClient, public myService: MyService) {
...
}
When we pass some params we always do it this way: 当我们传递一些参数时,我们总是这样做:
import { Router, ActivatedRoute } from '@angular/router';
constructor(
private router: Router,
private route: ActivatedRoute
){
this.route.params.subscribe(params => {
let todo = params['todo'];
});
}
Maybe you have to move the subscription to ngOnInit() but normally this should work. 也许您必须将预订移至ngOnInit(),但通常这应该可行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.