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

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

问题描述

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

谢谢,任何帮助将不胜感激.

解决方案

我使用查询参数创建了一个拉取请求.我会尽力解释我所做的一切.

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

首先我们需要更改您的index.html,将其添加到您的:

请参阅此处补充一下.

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

加载中...

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

import { Component } from '@angular/core';@零件({选择器:'根',模板:`<router-outlet></router-outlet>`,})导出类 RootComponent {构造函数(){}}

看,我们有 作为模板,Angular 将根据路由注入我们的组件.

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

import { Routes, RouterModule } from '@angular/router';从 './app.component' 导入 { AppComponent };导出 const mainRoutes: 路由 = [{ 路径:'',组件:AppComponent }];导出 const mainRoutingProviders: any[] = [];export const routing = RouterModule.forRoot(mainRoutes);

在这个文件中,我们说对于我们的基本路由,我们想要渲染我们的 AppComponent

我们已经创建了我们的新文件,现在我们需要在您的 app.module.ts 中告诉我们的 App Module 关于它们,所以我们导入新文件并声明新组件.我们还需要更改我们的 boostrap 组件:

从'@angular/core'导入{NgModule};从@angular/platform-b​​rowser"导入{BrowserModule};从@angular/forms"导入 {FormsModule, ReactiveFormsModule};从 './app.component' 导入 {AppComponent};从 './root.component' 导入 {RootComponent};//我们导入新的 RootComponent从'primeng/primeng'导入{ChartModule};从'primeng/primeng'导入{TooltipModule};从'./main.routes'导入{路由,mainRoutingProviders};//我们也导入我们的路由@NgModule({进口:[浏览器模块,图表模块,表单模块,mainRoutingProviders,//我们还需要将我们的路由提供者导入到模块中反应形式模块,路由,//并导入我们的路由声明工具提示模块],声明:[AppComponent, RootComponent],//我们声明我们的新 RootCpmcomponentbootstrap: [RootComponent]//请注意,我们现在正在使用 RootComponent 来引导我们的应用程序})导出类 AppModule {}

现在有了这一切,我们现在终于可以开始将参数传递给我们的应用程序,在您的 AppComponent 上导入 RouterActivatedRoute 和来自 @angular/routerParams 所以你的 AppComponent 看起来像这样:

import { Component, OnDestroy, OnInit } from '@angular/core';从'@angular/router' 导入 { Router, ActivatedRoute, Params };从rxjs/订阅"导入{订阅};导出类 AppComponent 实现 OnInit, OnDestroy {私有 var1:字符串;私有 var2:字符串;私人订阅:订阅;构造函数(私人路线:ActivatedRoute,专用路由器:路由器) {}ngOnInit() {//将订阅分配给一个变量,以便我们可以取消订阅以防止内存泄漏this.sub = this.route.queryParams.subscribe((params: Params) => {this.var1 = params['var1'];this.var2 = params['var2'];控制台日志(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天全站免登陆