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