【问题标题】:Passing variable or setting a variable by URL in Angular 2在 Angular 2 中通过 URL 传递变量或设置变量
【发布时间】:2017-03-15 21:09:55
【问题描述】:

我有一个用 Angular2 编写的应用程序。在一个组件中,有一个图表,您可以通过设置几个变量来调整它。我希望用户已经通过 URL 链接设置了这些变量的完整图表。

例如:localhost:4200/app/chart?height=500;width=400;color=blue

在我的组件中,有一些变量叫做:

this.height: number;
this.width: number;
this.color: string;

这是我的问题,如何在组件加载时从 URL 链接准确设置它们? (在初始化时)

我的第二个问题是,如何将这些变量传递到 URL 中?例如,我有这些变量:

this.height: number = 500;
this.width: number = 400;
this.color: string = blue;

如何将它们发送到 URL?让它看起来像:

localhost:4200/app/chart?height=500;width=400;color=blue`

我的路由文件:

import { Routes, RouterModule } from '@angular/router';

import { ChartComponent } from './chart/chart/index';

const appRoutes: Routes = [
  { path: 'app', component: AppComponent,
    children: [
      { path: 'chart', component: ChartComponent },
      { path: '', component: DashboardComponent }
    ]},

  // otherwise redirect to home
  { path: '**', redirectTo: '' }
 ];

export const routing = RouterModule.forRoot(appRoutes);

【问题讨论】:

  • 你能粘贴你的路由配置吗?我认为您的答案在于@angular/router 命名空间:)
  • @A1rPun 完成了我的朋友

标签: javascript angular variables url typescript


【解决方案1】:
constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.params.subscribe(
      (params: any) => {
        this.height: number = params['height'];
        this.width: number = params['width'];
        this.color: string = params['color'];
      }
    );
  }

【讨论】:

  • 放在哪里?在路由文件或我的图表组件中?
  • 在您使用它的组件中。不要忘记导入import {ActivatedRoute} from '@angular/router';
  • 没有这个使用当前的URL路由路径
  • 如果我想将这些变量发送到 url 怎么办?不仅下载?
  • @J.Doe this.router.navigate(['/chart', this.height, this.width, this.color]);
猜你喜欢
  • 1970-01-01
  • 2014-10-25
  • 2014-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-02
  • 2011-11-03
相关资源
最近更新 更多