How to pass 2 parameters from routerLink?

JMon picture JMon · Apr 20, 2017 · Viewed 7.4k times · Source

I am trying to pass 2 parameters through the routerLink, to my component and then to my service to get the data.

The Html looks like this:-

  <h3><a routerLink="['/repository', {{res.owner.login}}, {{res.name}} ]">{{res.owner.login}}</a></h3>

and in my component I have the following:-

ngOnInit() {
this._route.params
.map(params => params['userName,repoName'])
.subscribe((params) => {
  this.userName = params['userName']; this.repoName = params['repoName']
  console.log('params = ' + params)
  this._githubService.getRepo(params)
    .subscribe(repository => {
      this.repository = repository;
    })
  })
}

And in my service I have the following code:-

getRepo(params: any){
   let headers = new Headers();
   headers.append('Content-type', 'application/json');
   return this._http.get("https://api.github.com/repos/"+ params.userName +"/" + params.repoName+ "/commits&sort=stars&order=desc&page=1", { headers: headers, withCredentials: false })
      .map(this.extractRepo)
      .catch(error => this.handleError(error, this.router));

}

Router configuration is as follows:-

   import {ModuleWithProviders} from '@angular/core';
   import {Routes, RouterModule} from '@angular/router';

   import { HomeComponent } from '../app/components/home/home.component';
   import { RepositoryComponent } from 
    '../app/components/repository/repository.component';

   const appRoutes: Routes = [
       {path: '', component: HomeComponent, pathMatch: 'full'},
       {path: 'repository', component: RepositoryComponent}
   ];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);   

However when I run the application, the link is being displayed as follows:-

Error: Cannot match any routes. URL Segment: '%5B'/repository'%2C%20tetris%2C%20react-tetris%20%5D'

How can I format the routerLink and get the parameters to send to my service?

Thanks for your help and time!

Answer

Denko Mancheski picture Denko Mancheski · Apr 20, 2017

You need to put routerLink in [routerLink]. Because without the square brackets, its like you are binding to a string, and the string will be ['/repository', {{res.owner.login}}, {{res.name}} ] exactly this.

So whenever you try to bind something that existing in the class, you need to use []. Example: someVariable = 'http://etc..' than to bind it, you use [src]="someVariable". If you just do src="someVariable" this is not a valid link right, its just a string

Also, it will be useful if you post the router configuration above