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 ?
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);
});
});
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With