0

I'm trying to get a parameter serverId from the URL using the following setup:

    constructor(private peopleService: PeopleService, private route: ActivatedRoute) {
        this.route.paramMap.subscribe(params => {
            console.log(params); //params is empty here
             //...

Here's my setup in app.module.ts:

@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule, HttpClientModule, RouterModule.forRoot([])],
    providers: [],
    bootstrap: [AppComponent],
})

I've also tried using queryParams instead of paramMap, any method I've seen results in an empty parameter list so I'm assuming there's something wrong with my setup.

Is there something else I need to do to set this up? I'm providing the parameter correctly in the url as url?serverId=123.

muttley91
  • 12,278
  • 33
  • 106
  • 160

2 Answers2

0

If your routing Module is like this:

{
 path: 'url/:serverId ',
 component:MyComponent
}

so ,I guess that component is loaded before the actual routing applied. Please Add { enableTracing: true } to the RouterModule to see what is happening behind the scene.

RouterModule.forRoot([], { enableTracing: true })

then you can subscribe queryParams :

// ...
import { ActivatedRoute } from '@angular/router';
import 'rxjs/add/operator/filter';

@Component({ ... })
export class ProductComponent implements OnInit {
  serverId: string;
  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.queryParams
      .filter(params => params.serverId)
      .subscribe(params => {
        console.log(params); // { serverId: "123" }

        this.serverId= params.serverId;
        console.log(this.serverId); // 123
      }
    );
  }
}
Arash Hatami
  • 522
  • 4
  • 10
0

I found the issue. I had my app-routing-module.ts set up as follows:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }

which means that the imports in my app.module.ts should have read as follows:

imports: [BrowserModule, HttpClientModule, AppRoutingModule]
muttley91
  • 12,278
  • 33
  • 106
  • 160