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

标签 angular angular2-routing angular2-services

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

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

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

程序服务:(摘录)

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 但出于测试目的,这更合适。

最佳答案

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

关于angular - 获取服务中的第一个路由参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42015234/

相关文章:

angular - 405 Method Not Allowed and "CORS header ‘Access-Control-Allow-Origin’ missing“虽然tcpdump说它正在被发送出去

javascript - 我如何存储 JSON 对象或其特定值以供进一步使用(Angular)?我唯一能做的就是记录它们

angular - 如何在 Angular 2 中动态加载和显示包含 routerLink 指令的 html?

Angular2 Router v3,导航到不同的级别 : TypeError: Cannot read property '_routeConfig' of null

javascript - 全局服务在 angular2 中不起作用

angular - 为什么 Angular2 不能注入(inject)我的服务?

angular - 如何从所有消息的可观察对象中创建未读消息的可观察对象

angular - RouterLink 和 RouterLinkActive 如何工作?

javascript - 使用 angular 2 titleService 和服务器端渲染调用 setTitle 时为 500

javascript - Django - AngularJs 项目结构