【问题标题】:Get first route parameter in service获取服务中的第一个路由参数
【发布时间】:2017-02-03 01:20:36
【问题描述】:

我想要一个服务,它有一个可观察的,其变量依赖于当前 URL。

:programID                  --  program overivew
:programID/bug              --  bug list
:programID/bug/:bugID       --  bug overview

programID 可以随时切换。我提供了一项服务,据我从angular docs 了解到的,应该使用参数进行观察

ProgramService:(摘录)

currentProgramID: number

constructor(
    private router: Router,
    private route: ActivatedRoute,
    private http: Http){

    this.route.params.subscribe((params: Params) => {
        console.log('Parent:', params['programID'])
    })

    this.route.children[0].params.subscribe((params: Params) => {
        console.log('Childern:', params['programID'])
        //  Works if loaded while at url : 'abc123/bug/abc123'
    })

    this.route.params.subscribe((params: Params) => {
        console.log('Hacky?:', this.route.snapshot.params['programID'])
    })
}

需要当前程序引用的组件:(摘录)

program: Promise<program>

constructor(
    private programService: ProgramService, ... ){}

ngOnInit() {
    this.program = this.programService.getProgram(/*current program*/)
    ...
}

但是,我只得到一次programID,并且当页面以正确的 URL 加载时。导航后我什至不知道。

之后我将切换到switchMap,但出于测试目的,这更到位。

【问题讨论】:

    标签: angular angular2-routing angular2-services


    【解决方案1】:

    您可以使用router.eventsrouter.routerState.snapshot.root.firstChild阅读params

    @Injectable()
    class ProgramService {
      programId:string;
      constructor(
        private router: Router,
        //private http: Http
        ){
    
        this.router.events
        .filter(e => e instanceof NavigationEnd)
        .forEach(e =>{
          var firstChild = router.currentRouterState.snapshot.root.firstChild;
          console.log(firstChild.params);
          console.log(firstChild.firstChild && firstChild.firstChild.firstChild && firstChild.firstChild.firstChild.params);
          var newProgramId = firstChild.params['programID'];
          if(this.programId != newProgramId) {
            this.programId = newProgramId;
            this.programService.getProgram(this.programId);
          }
        });
    

    Plunker example

    【讨论】:

    • 这是真的,但是为什么 observable 不启动呢?并且是仅手动添加参数选项吗?
    • 服务只创建一次。每次应用导航到该组件的路由时,都会创建路由组件。这就是服务只注入一次ActivatedRoute 的原因。下次导航到此路由时,会创建一个新的 ActivatedRoute 实例,但服务仍保留旧的实例(除非在路由组件的 @Component() 中提供服务,这就是为什么 observable 没有火,因为它已经过时了。
    • 另外,您可以将服务注入路由组件,并让组件将参数传递给服务,而不是服务自己获取它。我对路由器没有深入的了解,可能还有其他我不知道的方法。
    • 我添加了一个 currentProgramID 参数,这样做的初衷是什么,以及每个组件都不需要 activeRoute...
    • 如果你将ActivatedRoute 传递给一个组件,并且你改变了路由使得only 参数值改变,那么这将发出一个新的值。如果您导航到不同的路线,组件将被销毁,因此订阅也将被销毁。这是唯一有用的用例,因为在这种情况下不会再次调用 ngOnInit() 和构造函数,因为组件实例被重用。
    猜你喜欢
    • 2018-01-11
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2021-12-12
    • 2013-05-24
    • 2017-01-22
    • 2021-10-30
    • 2020-08-04
    相关资源
    最近更新 更多