Finding parameters in Angular 4

I am working on implementing a multilanguage feature in an Angular app and I need to establish the default language when the site loads. The two languages supported are Spanish and English, with Spanish being the default language. In order to achieve this, I have the following routing setup:

const routes: Routes = [
  {
    path: ':lang', component: LanguageComponent,
    children: [
      { path: 'route1', component: Component1 },
      { path: 'route2', component: Component2 },
      { path: 'route3', component: Component3 },
      { path: 'route4', component: Component4 },
      { path: '', component: Component1 , pathMatch: 'full' },
    ],
  },
  { path: '', redirectTo: 'es', pathMatch: 'full' }
];

I am unsure if this structure of routing is correct for my requirements, which include using the same route for both languages and translating content at runtime using a custom translation service. One main issue I'm facing is that whenever I try to inspect the route params, they show as undefined. Here is how I'm trying to get the current language in my ngOnInit:

this.activatedRoute.params.subscribe((params: Params) => {
  this.currentLanguage = params['lang'];
});

I have also attempted this approach:

this.activatedRoute.params.subscribe((params) => {
  this.currentLanguage = params.lang;
});

I suspect that the problem lies in the redirection step, but I'm not certain how to set the ":lang" parameter during that redirect. Can you provide any insight or guidance on this issue?

Answer №1

In my opinion, a great approach would be to implement a service called AppTranslateService that manages the language settings defined in the LanguageComponent:

@Injectable()
export class AppTranslateService {
  public currentLang: string = 'en';
}

@Component({/*...*/})
export class LanguageComponent {
  constructor(appTranslateService: AppTranslateService, activatedRoute: ActivatedRoute) {
    activatedRoute.params.subscribe((params) => {
      appTranslateService.currentLang = params['lang'];
    });
  }
}

Then, you can simply access the appTranslateService.currentLang variable in other components.

Another option is to retrieve the desired parameter directly in your components using Angular's Router injection, for example: router.url.split('/')[1] (or perform this operation once in a shared service).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to dynamically load the child path of the Foo Component from a separate component using the current route data?

What I am in need of: The application includes a side-nav component, which contains a menu to load features and a sub-menu to load sub-features. Sub-features are considered as child routes of features. I have attempted to utilize a sample application wit ...

Loading an index.html file using Webpack 3, Typescript, and the file-loader: A step-by-step guide

Attempting to utilize the file-loader and Webpack 3 to load my index.html file is proving to be a challenge. The configuration in my webpack.config.ts file appears as follows: import * as webpack from 'webpack'; const config: webpack.Configura ...

JHipster's selection of radio button options

Within a jhipster project, I have an Enumeration field containing values "A, B, C, D, E". The conventional approach in Jhipster utilizes a Select/Options setup: <div class="form-group"> <label class="form-control-label" jhiT ...

What is the best way to utilize ngFor for iterating through a Map variable of classes in TypeScript?

In my TypeScript file, I have a class named `myMap` that contains a variable called `navList`, which is of type Map<string, string> and holds multiple key-value pairs. I am currently attempting to iterate over the values stored in `navList` within my ...

A guide on refreshing the dependencies list within Angular's node modules and package.json files

A close friend sent me the angular src folder, which I used to create a new Angular project. However, when I replaced my newly created src folder with my friend's and tried running the application using npm start, I encountered errors related to missi ...

Resolving conflict between a user-defined class name and a built-in class name

I am creating a TypeScript Map class that utilizes the built-in Map class along with generics. The problem arises when both classes have the same name. Is there a way to import the built-in Map using explicit namespace, similar to how it's done in Jav ...

Why is it that TypeScript does not issue any complaints concerning specific variables which are undefined?

I have the following example: class Relative { constructor(public fullName : string) { } greet() { return "Hello, my name is " + fullName; } } let relative : Relative = new Relative("John"); console.log(relative.greet()); Under certain circum ...

Is there a way to safeguard against accidental modifications to MatTab without prior authorization?

I need to delay the changing of the MatTab until a confirmation is provided. I am using MatDialog for this confirmation. The problem is that the tab switches before the user clicks "Yes" on the confirmation dialog. For instance, when I try to switch from ...

What could cause a member variable to be uninitialized in the ngInit method in Ionic/Angular, even though it was initially set in the constructor

Despite setting the modal form to be bound to an instance of "Foo" during its construction, I encountered a strange issue where, post-constructor, this.foo became undefined. Even after verifying this through breakpoints and console.log, the problem persist ...

Using TypeScript absolute imports from another project for standard TypeScript files and declarations at a global scope

We are currently considering migrating a large JavaEE code base to TypeScript. Within this environment, there are multiple projects with intricate directory structures and JavaScript code that heavily relies on global variables across all projects. Althou ...

"Slow loading times experienced with Nextjs Image component when integrated with a map

Why do the images load slowly on localhost when using map, but quickly when not using it? I've tried various props with the Image component, but none seem to solve this issue. However, if I refresh the page after all images have rendered once, they ...

What is the best way to focus on a particular version of TypeScript?

After upgrading my Angular 2 project to RC1 and the router to v3 alpha3, I encountered the following errors: node_modules/@angular/router/directives/router_outlet.d.ts(10,14): error TS1005: '=' expected. It appears to be a TypeScript version is ...

Angular Multiplexed Templates - Utilizing a Variety of Components

I'm looking to create a Multiple Template scenario, but I could really use some guidance. In this scenario, the User has the ability to change the entire template, meaning they can switch between Template 1, Template 2, Template 3, and so forth. Each ...

Data cannot be transferred to a child element unless it has been initialized during the definition phase

Passing an array data from parent to child component has brought up some interesting scenarios: parent.component.html: <child-component ... [options]="students" > </child-component> Status I: Setting the array on definition ...

I'm in the process of putting together a node.js project using typescript, but I'm a little unsure about the steps needed to

Currently, I am working on a node.js project that involves compiling with typescript. I recently realized that there is a directory named scripts dedicated to running various tasks outside of the server context, such as seed file operations. With files now ...

Is it Feasible to Use Component Interface in Angular 5/6?

My main goal is to create a component that can wrap around MatStepper and accept 2..n steps, each with their own components. In other languages, I would typically create an interface with common behavior, implement it in different components, and then use ...

Definition file for Typescript d.ts that includes optional properties in a function

Within my code, I have a function that offers different results based on specified options. These options dictate the type of return value. The function is currently written in plain JavaScript and I am looking to provide it with types using an index.d.ts ...

There are several InputBase elements nested within a FormControl

There seems to be an issue: Material-UI: It appears that there are multiple InputBase components within a FormControl, which is not supported. This could potentially lead to infinite rendering loops. Please only use one InputBase component. I understand ...

Is implementing client components in Server Side pages an effective strategy for optimizing SSR performance?

In order to overcome the challenge of using client-side components in server-side pages, I made the decision to create a client-side wrapper to encapsulate these components within server-side pages. This way, I can manage all API calls and data fetching on ...

Error in displaying dialogues upon clicking

Currently experimenting with creating a dialog modal using the tutorial found at https://github.com/gopinav/Angular-Material-Tutorial/tree/master/material-demo/src/app, specifically referring to the dialog-example and dialog folder. However, upon testing ...