我正在尝试构建一个类似于Google Map的以 map 为中心的应用程序。因此主要是一个 map ,根据URL路线,一个组件会加载到一个小的侧面板中。

export const routes: Routes = [
    {path: 'home/:coordinates', component: HomeComponent},
    {path: 'dashboard/:coordinates', component: DashboardComponent},
    {path: 'utils/:coordinates', component: UtilsDemo},
];

我想实现的目标类似于Google Maps:

/home/@54.072,-2.899->加载HomeComponent并导航至坐标54.072,-2.899

/dashboard/@53.123,2.345->加载DashboardComponent并导航到坐标54.123,2.345

但是,:coordinates参数不应在组件本地,而应在全局范围内。否则,我必须在每个组件中执行导航部分。

换句话说:如果我这样做:
this.route.params.subscribe(params => {
   console.log(params['coordinates']);
});

AppComponent内部,未定义参数。它仅在每个特定组件内部起作用。

在Angular5中有什么方法可以做到这一点?

最佳答案

也许Route Resolver是您的选择。它通常用于在导航到路由之前从服务器获取数据,但是您可以将导航逻辑放在其中。

  • 为您的导航逻辑
  • 创建服务NavigationResolver
  • 该服务实现Resolve接口(interface)。
  • resolve方法中,您提取参数并启动导航逻辑
    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Crisis> {
      let coordinates = route.paramMap.get('coordinates');
    
      // This is where your navigation happens
      return this.navigateTo(coordinates)
    }
    
  • 您将NavigationResolver添加到应处理参数的所有路由中:
    {
      path: 'home/:coordinates',
      component: HomeComponent,
      resolve: {
        navigationResult: NavigationResolver
      }
    },
    
  • 如有必要,您可以通过以下方式从组件内部访问已解析的导航数据:
    ngOnInit() {
      this.route.data
        .subscribe((data: { navigationResult: NavigationResult }) => {
          this.navigation = data.navigationResult;
        });
    }
    

  • 在官方docs中阅读有关Route Resolvers的更多信息。

    关于javascript - Angular 路由器中全局可用的URL参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50154351/

    10-12 17:52
    查看更多