【发布时间】:2018-08-30 05:32:27
【问题描述】:
我有一项服务,可以从 URL 中读取几个参数。看起来不错,直到我尝试在app.component.ts 的constructor 中注入服务,或者我尝试从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) {
...
}
【问题讨论】:
-
如果你尝试解析
ngOnInit钩子中的URL怎么办? -
@trichetriche:
ngOnInit()在app.component.ts?我确实试了一下,但没有用。问题正是当我在app.component.ts构造函数中注入服务时。 -
否,在服务的
ngOninit中。 -
@tricheriche:不幸的是它没有帮助......服务甚至没有触发
ngOnInit(),所以我什至不能console.log('param1: ' + this.param1)。换句话说,什么也没有发生。
标签: angular typescript url-parameters