Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 ParamMap not working on app.component.ts

I want to get id from route params but it return null as value.

app.component.ts:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {    
  constructor(private route: ActivatedRoute) { }

    ngOnInit(){  
    const id = this.route.snapshot.paramMap.get('idC');
    console.log(id);
}

routing.ts:

{ path: 'profile/:idC', component: AccountComponent }

The aim of code on app.component is because I'm using navbar on app so when a user is connected, the expected result is to get id from route so that navbar will display "Welcome user1". Any solution ?

like image 305
Atom Avatar asked Aug 27 '18 08:08

Atom


2 Answers

You can also get params value without service

constructor(private router: Router, private route: ActivatedRoute) {}

ngOnInit() {

 this.router.events.subscribe((event: any) => {
    let r = this.route;
    while (r.firstChild) {
        r = r.firstChild
    }
    r.params.subscribe(params => {
        console.log(params.idC);
    });
  });

}
like image 149
Aniket Avhad Avatar answered Sep 19 '22 13:09

Aniket Avhad


You can pick idC from your AccountComponent and assign the value to a property inside service.

account.component.ts

constructor(private route: ActivatedRoute, myService: MyService) { }

ngOnInit(){  
  const id = this.route.snapshot.paramMap.get('idC');
  this.myService.id = id;
  console.log(id);
}

Access the same service from your AppComponent and use that variable inside your HTML.

For example, inside your app.component.ts

constructor(private route: ActivatedRoute, myService: MyService) { }

and your app.component.html

<p>ID: {{myService.id}}</p>
like image 30
Ankit Sharma Avatar answered Sep 20 '22 13:09

Ankit Sharma