【问题标题】:Angular 2 RC1: Get parameters from the initial URL usedAngular 2 RC1:从使用的初始 URL 获取参数
【发布时间】:2016-05-13 20:16:39
【问题描述】:

一些用户通过邀请进入我的网络应用。所以他们会有一个看起来像这样的链接:https://example.com/invitaion/12345 其中 12345 是他们唯一的邀请号码。

当用户点击链接,并且我的 AppComponent 在客户端被框架初始化时,我如何获得使用的 URL 是“invitation/*”这一事实以及如何获得邀请号码?

【问题讨论】:

    标签: angular


    【解决方案1】:

    AppComponent 中的新路由器(>= RC.0)中,可以使用

      import 'rxjs/add/operator/first';
      ....
    
      constructor(private router:Router, private routeSerializer:RouterUrlSerializer, private location:Location) {
        router.changes.first().subscribe(() => {
    
        let urlTree = this.routeSerializer.parse(location.path());
          console.log('id', urlTree.children(urlTree.children(urlTree.root)[0])[0].segment);
        });
      }
    

    (获取第二段)

    MyComponent 这更容易:

    routerOnActivate(curr:RouteSegment, prev?:RouteSegment, currTree?:RouteTree, prevTree?:RouteTree):void {
      this.id = curr.getParam('id');
    }
    

    【讨论】:

      【解决方案2】:

      您需要使用RouteParams 来访问该变量,并在您的组件中使用它。

      // let's assume you labeled it as `path : '/invitation/:id'` in your @Route setup.
      
      @Route([
          { path : '/invitation/:id', component : MyComponent }
      ]) 
      

      现在在组件内部:

      import { RouteParams } from '@angular/router';
      
      // Now simply get the ID when injecting RouteParams within your constructor
      
      class MyComponent {
          id: string;
          constructor(_params: RouteParams) {
              this.id = _params.get('id');
          }
      }
      

      【讨论】:

      • 您可能需要尝试从 @angular/router-deprecated 导入 RouteParams 如果这不起作用,请告诉我!
      • 我知道这是一个旧响应,但导入对我不起作用:Module ../../../../../node_modules/@angular/router/router"' has no exported member 'RouteParams'.ts(2305) @angular/router-deprecated 相同
      猜你喜欢
      • 1970-01-01
      • 2017-07-16
      • 2017-12-14
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-29
      • 1970-01-01
      相关资源
      最近更新 更多