Javascript Angular 2 - 如何传递 URL 参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39858471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2 - How to pass URL parameters?
提问by jjj
I have created a single page mortgage calculator application in Angular 2, which acts like a learning playground for me (trying to get more accustomed to technology stack currently used at work)... It's running at http://www.mortgagecalculator123.comif you want to look at it. I've made it open source with a Fork Me link right on the page if you want to look at it.
我在 Angular 2 中创建了一个单页抵押计算器应用程序,它对我来说就像一个学习游乐场(试图更加习惯目前在工作中使用的技术堆栈)......它在http://www.mortgagecalculator123.com上运行如果你想看的话。如果您想查看它,我已经在页面上通过 Fork Me 链接将其开源。
Anyhow, what I want to do, is to be able to pass variables to my app, straight from the URL, so they can be consumed by my Angular 2 app. Something like this: http://www.mortgagecalculator123.com/?var1=ABC&var2=DEF
无论如何,我想要做的是能够直接从 URL 将变量传递给我的应用程序,以便我的 Angular 2 应用程序可以使用它们。像这样:http: //www.mortgagecalculator123.com/?var1=ABC&var2 =DEF
I've tried following, in my app.component.ts, I've added following:
我试过,在我的 app.component.ts 中,我添加了以下内容:
import { Router, ActivatedRoute, Params } from '@angular/router';
AppComponent {
private var1: string;
private var2: string;
constructor(
private route: ActivatedRoute,
private router: Router
) {}
ngOnInit() {
this.route.params.forEach((params: Params) => {
this.var1 = params['var1'];
this.var2 = params['var2'];
});
console.log(this.var1, this.var2);
}
...
}
But this won't work, when I run npm start, I get following error:
但这不起作用,当我运行npm start 时,出现以下错误:
aot/app/app.component.ngfactory.ts(45,30): error TS2346: Supplied parameters do not match any signature of call target.
aot/app/app.component.ngfactory.ts(45,30): 错误 TS2346: 提供的参数与调用目标的任何签名都不匹配。
Thank you, any help would be much appreciated.
谢谢,任何帮助将不胜感激。
回答by Fabio Antunes
I created a pull request with the query params working. I will try to explain everything I did.
我创建了一个带有查询参数工作的拉取请求。我会尽力解释我所做的一切。
The reason why the previous answers doesn't work is because you aren't using the router at all. You created a massive app component without routes. To fix that we need to start using the route module, I also advise you to read these two tutorials: Routingand Routing & Navigation.
以前的答案不起作用的原因是因为您根本没有使用路由器。您创建了一个没有路由的大型应用程序组件。为了解决这个问题,我们需要开始使用 route 模块,我还建议您阅读这两个教程:Routing和Routing & Navigation。
First we need to change your index.html
, add this to your <head>
:
首先,我们需要更改您的index.html
,将其添加到您的<head>
:
<base href="/">
See herewhy it's important to add that.
见这里为什么要补充一点,这一点很重要。
Then since you are using your AppComponent
to show everything we need to create a new component, which we will call RootComponent
. On your index.html
change <my-app>
to <root>
; it will look like this:
然后,由于您正在使用您的AppComponent
来显示我们创建一个新组件所需的一切,我们将其称为RootComponent
. 在您index.html
更改<my-app>
为<root>
; 它看起来像这样:
<root>Loading...</root>
Now inside your app
folder we need to create two files the first one will be root.component.ts
which will look like this:
现在在您的app
文件夹中,我们需要创建两个文件,第一个文件root.component.ts
如下所示:
import { Component } from '@angular/core';
@Component({
selector: 'root',
template: `<router-outlet></router-outlet>`,
})
export class RootComponent {
constructor() { }
}
Look that we have the <router-outlet></router-outlet>
as a template, Angular will inject our components based on the route.
看看我们有<router-outlet></router-outlet>
一个模板,Angular 将根据路由注入我们的组件。
We still need to create one more file, which will be main.route.ts
, this is what it looks like:
我们还需要再创建一个文件,它是main.route.ts
,它是这样的:
import { Routes, RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
export const mainRoutes: Routes = [
{ path: '', component: AppComponent }
];
export const mainRoutingProviders: any[] = [];
export const routing = RouterModule.forRoot(mainRoutes);
In this file we are saying that for our base route, we want to render our AppComponent
在这个文件中,我们说对于我们的基本路线,我们想要渲染我们的 AppComponent
We have created our new files, now we need to tell our App Moduleabout them, in your app.module.ts
so we import the new files and declare the new component. We also need to change our boostrap component:
我们已经创建了我们的新文件,现在我们需要告诉我们的App Module关于它们,app.module.ts
所以我们导入新文件并声明新组件。我们还需要更改我们的 boostrap 组件:
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {FormsModule, ReactiveFormsModule} from "@angular/forms";
import {AppComponent} from './app.component';
import {RootComponent} from './root.component'; // we import our new RootComponent
import {ChartModule} from 'primeng/primeng';
import {TooltipModule} from 'primeng/primeng';
import { routing, mainRoutingProviders } from './main.routes'; // We also import our Routes
@NgModule({
imports: [
BrowserModule,
ChartModule,
FormsModule,
mainRoutingProviders, // we also need to import our route provider into the module
ReactiveFormsModule,
routing, // and also import our routes declarations
TooltipModule
],
declarations: [AppComponent, RootComponent], // we declare our new RootCpmponent
bootstrap: [RootComponent] // Notice that we are now using our RootComponent to bootstrap our app
})
export class AppModule {
}
Now with all this in place we can now finally start passing parameters to our app, on your AppComponent
import the Router
, ActivatedRoute
and the Params
from @angular/router
so your AppComponent
will look something like this:
现在,这一切的地方,我们现在终于可以开始参数传递到我们的应用程序,你的AppComponent
进口Router
,ActivatedRoute
而Params
从@angular/router
让你AppComponent
看起来是这样的:
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
export class AppComponent implements OnInit, OnDestroy {
private var1: string;
private var2: string;
private sub: Subscription;
constructor(
private route: ActivatedRoute,
private router: Router
) {}
ngOnInit() {
// assign the subscription to a variable so we can unsubscribe to prevent memory leaks
this.sub = this.route.queryParams.subscribe((params: Params) => {
this.var1 = params['var1'];
this.var2 = params['var2'];
console.log(this.var1, this.var2);
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
...
}
You can see the pull request here
你可以在这里看到拉取请求
回答by micronyks
It seems you are dealing with Queryparams. So to access them, you can try below code,
看来您正在处理Queryparams。所以要访问它们,您可以尝试以下代码,
this.var1= this.route
.queryParams
.map(params => params['var1']);