Angular 2 - How to pass URL parameters?

后端 未结 2 1347
半阙折子戏
半阙折子戏 2020-11-28 07:27

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 cu

相关标签:
2条回答
  • 2020-11-28 08:20

    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

    0 讨论(0)
  • 2020-11-28 08:25

    It seems you are dealing with Queryparams . So to access them, you can try below code,

    this.var1= this.route
          .queryParams
          .map(params => params['var1']);
    
    0 讨论(0)
提交回复
热议问题