i'm new with Angular 5. So i'm trying to extract the id from the url so i can send it to a php file and then get back some data from a database.
import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-a-usuario',
templateUrl: './a-usuario.component.html',
styleUrls: ['./a-usuario.component.css']
})
export class AUsuarioComponent implements OnInit {
urlop = 'http://localhost/crudu/mostrarID.php';
datos: any;
id: number;
constructor(private http: HttpClient, private router: Router, private route: ActivatedRoute) {
}
ngOnInit() {
this.route.params.subscribe(params => {
this.id = params['id']; // (+) converts string 'id' to a number
});
console.log(this.id);
}
}
I've been trying any solution but it doesn't work (in console log it shows NaN or Undefined)
const appRoutes: Routes = [
{'path': 'admin', component: AdminComponent},
{'path': 'eUsuario', component: AUsuarioComponent, children: [{
path: ':id',
component: AUsuarioComponent
}]},
{'path': 'iUsuario', component: IUsuarioComponent},
{path: '',
redirectTo: '/',
pathMatch: 'full'},
];
All you need to do is move the console.log inside the subscribe to see the value. Trying to access the value outside of the params.subscribe will not work, as you have discovered. See below.
ngOnInit() {
this.routeListener = this.route.params.subscribe(params => {
this.id = +params['id']; // (+) converts string 'id' to a number
console.log(this.id);
});
}
Later inside ngOnDestroy, unsubscribe to prevent memory leaks, like:
ngOnDestroy() {
this.routeListener.unsubscribe();
}
Any other actions you want to take with what is returned from params['id'] value would need to happen within the subscribe, too.
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