【问题标题】:Why does service injection in app component cause undefined for URL parameters?为什么应用程序组件中的服务注入导致 URL 参数未定义?
【发布时间】:2018-08-30 05:32:27
【问题描述】:

我有一项服务,可以从 URL 中读取几个参数。看起来不错,直到我尝试在app.component.tsconstructor 中注入服务,或者我尝试从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


【解决方案1】:

当我们传递一些参数时,我们总是这样做:

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

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

也许您必须将订阅移动到 ngOnInit() 但通常这应该可以工作。

【讨论】:

  • 我确实在服务中尝试过,但不幸的是它没有帮助......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-08
  • 2019-03-29
  • 2018-04-07
  • 2015-07-10
  • 2011-04-08
  • 2022-11-16
  • 2012-03-29
相关资源
最近更新 更多