Angular 2 - 如何传递URL参数? [英] Angular 2 - How to pass URL parameters?

查看:174
本文介绍了Angular 2 - 如何传递URL参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular 2中创建了一个单页抵押贷款计算器应用程序,它对我来说就像一个学习操场(试图更习惯于目前在工作中使用的技术堆栈)......它运行在



谢谢,非常感谢任何帮助。

解决方案

我创建了拉取请求与查询参数工作。我将尝试解释我所做的一切。



之前的答案不起作用的原因是因为你根本没有使用路由器。您创建了一个没有路由的庞大应用组件。为了解决这个问题,我们需要开始使用路由模块,我还建议你阅读这两个教程:路由路由&导航



首先我们需要更改 index.html ,将其添加到< head>

 < base href =/> 

参见这里为什么重要的是添加它。



然后因为你正在使用你的 AppComponent 显示我们创建新组件所需的一切,我们将调用 RootComponent 。在 index.html 上将< my-app> 更改为< root> ;它将如下所示:

 < root> Loading ...< / root> 

现在我们需要在 app 文件夹中创建两个文件,第一个文件将是 root.component.ts ,如下所示:

 从'@ angular / core'导入{Component}; 

@Component({
选择器:'root',
模板:`< router-outlet>< / router-outlet>`,
})
导出类RootComponent {
constructor(){}
}

看看我们将< router-outlet>< / router-outlet> 作为模板,Angular将根据路线注入我们的组件。



我们还需要再创建一个文件,它将是 main.route.ts ,这就是它的样子: / p>

 从'@ angular / router'导入{Routes,RouterModule};来自'./app.component'的
import {AppComponent};

export const mainRoutes:Routes = [
{path:'',component:AppComponent}
];
export const mainRoutingProviders:any [] = [];
export const routing = RouterModule.forRoot(mainRoutes);

在这个文件中我们说我们的基本路线要渲染 AppComponent



我们创建了新文件,现在我们需要告诉应用模块,在 app.module.ts 中,我们导入新文件并声明新组件。我们还需要更改我们的boostrap组件:

 从'@ angular / core'导入{NgModule};来自'@ angular / platform-b​​rowser'的
import {BrowserModule};
从@ angular / forms导入{FormsModule,ReactiveFormsModule};来自'./app.component'的
import {AppComponent};来自'./root.component'的
import {RootComponent}; //我们从'primeng / primeng'导入新的RootComponent
import {ChartModule};来自'primeng / primeng'的
import {TooltipModule};来自'./main.routes'的
import {routing,mainRoutingProviders}; //我们还导入我们的路线

@NgModule({
进口:[
BrowserModule,
ChartModule,
FormsModule,
mainRoutingProviders, //我们还需要将我们的路由提供者导入模块
ReactiveFormsModule,
routing,//并导入我们的路由声明
TooltipModule
],
声明: [AppComponent,RootComponent],//我们声明新的RootCpmponent
引导程序:[RootComponent] //注意我们现在使用RootComponent来引导我们的应用程序
})
导出类AppModule {
}

现在有了这一切,我们现在终于可以开始将参数传递给我们的应用了,在 AppComponent 上导入路由器 ActivatedRoute Params 来自 @ angular / router 所以你的 AppComponent 会看起来类似这样的事情:

  import {Component,OnDestroy,OnInit}来回m'@ angular / core';来自'@ angular / router'的
import {Router,ActivatedRoute,Params};
从'rxjs / Subscription'导入{Subscription};

导出类AppComponent实现OnInit,OnDestroy {
private var1:string;
private var2:string;
private sub:订阅;

构造函数(
私有路由:ActivatedRoute,
私有路由器:路由器
){}

ngOnInit(){
//将订阅分配给变量,以便我们可以取消订阅以防止内存泄漏
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();
}
...
}

你可以看到请求此处


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.

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

I've tried following, in my app.component.ts, I've added following:

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:

aot/app/app.component.ngfactory.ts(45,30): error TS2346: Supplied parameters do not match any signature of call target.

Thank you, any help would be much appreciated.

解决方案

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

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

<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 new component, which we will call RootComponent. On your index.html change <my-app> to <root>; it will look like this:

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

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:

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

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:

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:

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

这篇关于Angular 2 - 如何传递URL参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆