首页 文章

如何使用Angular 2 Dart在页面重新加载时支持RouteParams?

提问于
浏览
12

我在Angular 2 Dart中使用Router和RouteParams .

我的路线如下:

@RouteConfig(const [
  const Route(path: '/', component: ViewLanding, as: 'home'),
  const Route(path: '/landing', component: ViewLanding, as: 'landing'),
  const Route(path: '/flights', component: ViewFlights, as: 'flights'),
  const Route(path: '/picker/:cityDepart/:cityArrival/:dateDepart/:dateArrival/', component: ViewFlights, as: 'picker'),
  const Route(path: '/order/:id/:level/:dateDepart/:dateArrival/', component: ViewOrder, as: 'order'),
  const Route(path: '/order/complete', component: ViewComplete, as: 'orderComplete')
])

//应用程序入口点:

void main() {
  print('-- Main.dart 2 --');
  bootstrap(Tickets, [
    routerInjectables,
    client_classes,
    // The base path of your application
    bind(APP_BASE_HREF).toValue('/'),
    // uncomment this if you want to use '#' in your url
    bind(LocationStrategy).toClass(HashLocationStrategy)
  ]);
}

这适用于router-outlet / router-link / router.navigate

但是,在页面重新加载时 - 我没有得到与params的路线的正面匹配 . IE:如果我刷新 http://localhost:8080/#/picker/SAN/SFO/2015-01-01/2015-04-02 - 我转到没有子路由的父视图 . 任何具有params的路线都会出现这种症状 .

直接导航或刷新到: http://localhost:8080/#/flights/ - 按预期工作 - 实例化ViewFlights组件

Symptoms: 使用params的路由失败 .

Question: 如何定义路由配置以在刷新时使用参数

Links: https://github.com/rightisleft/web_apps_dart/blob/angular2/web/main.dart https://github.com/rightisleft/web_apps_dart/blob/angular2/lib/client/tickets.dart

1 回答

  • 0

    如果我正确理解您的问题,您需要订阅组件中的路由器事件以使用new更新旧的params,然后更新您的UI .

    我假设你的问题是当你打开一个网址 http://localhost:8080/#/picker/SAN/SFO/2015-01-01/2015-04-02 ,然后导航到 http://localhost:8080/#/picker/SAN/SFO . 您所做的是更改路径,但组件已经实例化,这意味着新的参数不会被更新(也不会被删除) . 我通常在您的父组件中执行以下操作

    Angular 5

    constructor(private router:Router){
     // Subscribe to the router events. 
     // It may be a good idea to assign this subscription to a variable, and then do an unsubscribe in your ngOnDestroy().
     this.router.events.subscribe(event=>{ 
      if(event instanceof ActivationEnd){
       var cityDepart = event.snapshot.params["cityDepart"];
       var cityArrival = event.snapshot.params["cityArrival"];
       var dateDepart = event.snapshot.params["dateDepart"]; 
       var dateArrival = event.snapshot.params["dateArrival"];
       // do some logic
      }
     });
    }
    

相关问题