角2 -如何传递URL参数?

时间:2022-03-02 15:16:09

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.com if 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.

我已经创建了一个单页抵押计算器应用在角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传递变量到我的应用程序,这样它们就可以被我的角2应用程序使用

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

角2 -如何传递URL参数?

Thank you, any help would be much appreciated.

谢谢,任何帮助都将不胜感激。

2 个解决方案

#1


41  

I created a pull request with the query params working. I will try to explain everything I did.

我使用查询params创建了一个pull请求。我会尽力解释我所做的一切。

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: Routing and Routing & Navigation.

之前的答案之所以无效,是因为你根本不用路由器。你创建了一个庞大的没有路由的应用程序组件。为了解决这个问题,我们需要开始使用route模块,我还建议您阅读这两个教程:Routing and Routing & Navigation。

First we need to change your index.html, add this to your <head>:

首先我们需要改变你的索引。html,添加到你的:

<base href="/">

See here why it's important to add that.

看这里,为什么要加上这个。

Then since you are using your AppComponent to show everything we need to create a need component, which we will call RootComponent. On your index.html substitute the <my-app> by <root>; it will look like this:

然后,由于您正在使用AppComponent来显示创建需要组件所需的所有内容,因此我们将其称为RootComponent。在你的索引。html将 替换为 ;它看起来是这样的:

<root>Loading...</root>

Now inside your app folder we need to create two files the first one will 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.

看,我们有 作为模板,角将根据路径注入我们的组件。

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 Module about 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:

我们已经创建了新的文件,现在我们需要告诉我们的应用程序模块,在你的应用程序模块中。所以我们导入新的文件并声明新的组件。我们还需要改变我们的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上,导入路由器,ActivatedRoute和@ angle / Router的Params,这样你的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

你可以在这里看到拉动请求

#2


0  

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

#1


41  

I created a pull request with the query params working. I will try to explain everything I did.

我使用查询params创建了一个pull请求。我会尽力解释我所做的一切。

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: Routing and Routing & Navigation.

之前的答案之所以无效,是因为你根本不用路由器。你创建了一个庞大的没有路由的应用程序组件。为了解决这个问题,我们需要开始使用route模块,我还建议您阅读这两个教程:Routing and Routing & Navigation。

First we need to change your index.html, add this to your <head>:

首先我们需要改变你的索引。html,添加到你的:

<base href="/">

See here why it's important to add that.

看这里,为什么要加上这个。

Then since you are using your AppComponent to show everything we need to create a need component, which we will call RootComponent. On your index.html substitute the <my-app> by <root>; it will look like this:

然后,由于您正在使用AppComponent来显示创建需要组件所需的所有内容,因此我们将其称为RootComponent。在你的索引。html将 替换为 ;它看起来是这样的:

<root>Loading...</root>

Now inside your app folder we need to create two files the first one will 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.

看,我们有 作为模板,角将根据路径注入我们的组件。

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 Module about 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:

我们已经创建了新的文件,现在我们需要告诉我们的应用程序模块,在你的应用程序模块中。所以我们导入新的文件并声明新的组件。我们还需要改变我们的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上,导入路由器,ActivatedRoute和@ angle / Router的Params,这样你的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

你可以在这里看到拉动请求

#2


0  

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