1

I have two components and i want to send a variable from one to the other using a route parameter. In my first component I use this function to send the id:

sendId(id : string) : void {
    this.router.navigate(['/component2', id]);
}

My routing module looks like this:

const routes: Routes = [
 { path: 'component2/:id', component: Component2},
 { path: '**', redirectTo: '' }
];

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

export class AppRoutingModule {}

And in my second component I'm trying to read it like this:

import { Router, ActivatedRoute, Params } from '@angular/router';

export class Component2 implements OnInit {
   id: string;

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

ngOnInit() {
    this.route.params.subscribe(params => { this.id = +params['id']; 
    });

    console.log(this.id);
}

But I receive a null value. What am i missing?

2 Answers 2

5

Because console.log(this.id); works before you get the value from the route. Put the console.log into the subscribe function

ngOnInit() {
    this.route.params.subscribe(params => { 
        this.id = +params['id']; 
        console.log(this.id);
    });  
}
Sign up to request clarification or add additional context in comments.

1 Comment

i still get null when putting console.log inside
1

I managed to do it by changing my component2 code like this:

import { Router, ActivatedRoute, Params } from '@angular/router';

export class Component2 implements OnInit {
   id: string;
   private sub: any;    <---- add subcriber

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

ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
        this.id = params['id'];   <---- remove '+'
});

console.log(this.id);
}

I added the subscriber and removed the '+' from params['id']

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.