获取服务中的第一个路由参数

时间:2017-02-03 01:20:36

标签: angular angular2-routing angular2-services

我想要一个服务,它有一个可观察的变量,其变量取决于当前的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,但出于测试目的,这已经到位了。

1 个答案:

答案 0 :(得分:5)

您可以使用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