raju
raju

Reputation: 6936

How to pass and receive data using router.navigate with Angular?

I am trying to pass and read data using Angular Route.navigate ,

On one component I have

this._router.navigate(["dashboard",{ queryParams: { page: 1 }}],

On Dashboard component I have

ngOnInit() {
    this.sub = this._route
      .queryParams
      .subscribe(params => {
        // Defaults to 0 if no query param provided.
        let page = +params['page'] || 0;
        console.log(page);
      });
  }

But this always return 0

Am I doing anything wrong?

My ng --version is

@angular/cli: 1.0.2
node: 6.3.1
os: darwin x64
@angular/common: 4.1.1
@angular/compiler: 4.1.1
@angular/core: 4.1.1
@angular/forms: 4.1.1
@angular/http: 4.1.1
@angular/platform-browser: 4.1.1
@angular/platform-browser-dynamic: 4.1.1
@angular/router: 4.1.1
@angular/cli: 1.0.2
@angular/compiler-cli: 4.1.1
IPLCEWKS01167:routeTest iplcewks01167$

Upvotes: 1

Views: 3243

Answers (4)

singh_v
singh_v

Reputation: 172

Angular 7.2.0 introduced new way of passing the data when navigating between routed components without the data being a part of the query string.

Sending the data

export class ComponentA {
    constructor(private router: Router) {}
    goToComponentB(): void {
        this.router.navigate(['routePath'], {state: {data: {...}}});
    }
}

Receiving the data

You can read the data from browser’s history object in the constructor:

constructor(){
   Console.log(history.state.data);
}

Reference - https://medium.com/ableneo/how-to-pass-data-between-routed-components-in-angular-2306308d8255

Upvotes: 0

Rahul Singh
Rahul Singh

Reputation: 19622

Try this

{ path: 'a4/:message', component:  Angular4Component, data:{ ping:'passedvia router'}}

fetch it in the component using this.message = this.route.snapshot.params['message'];

this is the file in which it is used in the repo .

https://github.com/rahulrsingh09/AngularConcepts/blob/master/src/app/angular4/angular4.component.ts

The working example for the same - https://rahulrsingh09.github.io/AngularConcepts

Upvotes: 0

Harleen Kaur Arora
Harleen Kaur Arora

Reputation: 2087

Try this :-

this.router.navigate(['/dashboard', { queryParams: { page: 1 }} ]);

Upvotes: 1

Pengyy
Pengyy

Reputation: 38161

queryParams should be the second parameter for navigate.

replace this line

this._router.navigate(["dashboard",{ queryParams: { page: 1 }}];

to

this._router.navigate(["dashboard"], { queryParams: { page: 1 }});

Upvotes: 2

Related Questions