javascript - 在 Angular 2 中通过 URL 传递变量或设置变量

标签 javascript angular variables url typescript

我有一个用 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);

最佳答案

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'];
      }
    );
  }

关于javascript - 在 Angular 2 中通过 URL 传递变量或设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42820721/

相关文章:

对象外的JavaScript函数封装

javascript - 在 JSON 中编码日期的最佳实践是什么?

Angular 通用预渲染导致 301 重定向

for-loop - 批处理,如何执行存储在变量或txt文件中的代码?

ios - 在方法之间传递数组中的数据

javascript - 如何在 MongoDB 的 V8 引擎中创建可通过 db.eval 访问的全局对象?

javascript - 如何更新ReactJS中嵌套在对象内的数组的属性

javascript - 如何通过减去 2 个要在 timeOut 函数中使用的日期来获得剩余的毫秒数?

javascript - 防止 Angular 4 破坏 View / Controller

python - 另一个 Python 变量范围问题