Search code examples
angulartypescriptangular-router

Reading route parameters?


I am new to the Angular. Here we go:

const routes: Routes = [
  { path: '', redirectTo: '/ru/courses/categories', pathMatch: 'full' },
  { path: ':l/courses/categories', component: CourseCategoriesListComponent }
];

Then I got something injectable, something responsible for providing correct translation:

@Injectable()
export class LanguageService {
  constructor(public activatedRoute: ActivatedRoute) { }

  private readonly map: { [languageCode: string]: (() => TranslatorBase) } = {
    ru: () => new RussianTranslagor()
  };

  getTranslatorForCurrentLanguage(callback: (translatorBase: TranslatorBase) => void): void {
    this.activatedRoute.queryParams.subscribe(
      params => {
        console.log(params);
        // HERE IS THE PROBLEM!!!
        const lang = params['l'];
        if (lang) {
          callback(this.map[lang]());
        }
      }
    );
  }
}

When I run my server and get to a localhost:xxxxx, queryParams returns empty params object, such that I can't read actual value of the :l route parameter. Am I doing something wrong there?

UPDATE: I am trying to read :l parameter, which is short for "language". ;)


Solution

  • The problem here is that you're using queryParams instead of params. queryParams represents the query-string parameters, but your l parameter is just a normal parameter and so should be obtained through params (or paramMap).