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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:59:03  来源:igfitidea点击:

Angular 2 - How to pass URL parameters?

javascriptnode.jsangularnpm

提问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: 提供的参数与调用目标的任何签名都不匹配。

enter image description here

在此处输入图片说明

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 模块,我还建议您阅读这两个教程:RoutingRouting & 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 AppComponentto show everything we need to create a new component, which we will call RootComponent. On your index.htmlchange <my-app>to <root>; it will look like this:

然后,由于您正在使用您的AppComponent来显示我们创建一个新组件所需的一切,我们将其称为RootComponent. 在您index.html更改<my-app><root>; 它看起来像这样:

<root>Loading...</root>

Now inside your appfolder we need to create two files the first one will be root.component.tswhich 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.tsso 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 AppComponentimport the Router, ActivatedRouteand the Paramsfrom @angular/routerso your AppComponentwill look something like this:

现在,这一切的地方,我们现在终于可以开始参数传递到我们的应用程序,你的AppComponent进口RouterActivatedRouteParams@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']);