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

Adding Custom CSS File to an iFrame in Angular

Currently, I am attempting to include a CSS file in a third-party iframe to modify its styling. My initial idea was to employ the following code snippet: ngOnInit() { ... this.myIframe.nativeElement.document.head.appendChild('style.css') } U ...

Merging Promises in Typescript

In summary, my question is whether using a union type inside and outside of generics creates a different type. As I develop an API server with Express and TypeScript, I have created a wrapper function to handle the return type formation. This wrapper fun ...

Issue encountered with Angular 12 Material table: The data source provided does not match an array, Observable, or DataSource

When my REST API returns the following data: { "id": 1, "userId": 1, "date": "2020-03-02T00:00:02.000Z", "products": [ { "productId": 1, "quantity": 4 }, { "productId": 2, "quantity": 1 }, { "productId": 3, "quantity": 6 } ], "__v": 0 }, I attempt to imple ...

Definition for a function within a specific namespace that returns the specified object

Seeking to define the type of a function within a namespace (L.DomEvent.on(e)) that returns this, I encountered an issue with my JavaScript source code: L.DomEvent = { // @function on(el: HTMLElement, eventMap: Object, context?: Object): this on: ...

Leveraging the power of TypeScript and Firebase with async/await for executing multiple

Currently, I am reading through user records in a file line by line. Each line represents a user record that I create if it doesn't already exist. It's possible for the same user record to be spread across multiple lines, so when I detect that it ...

Eliminate perfect-scrollbar functionality on mobile devices

I have applied the perfect-scrollbar class with 'height: auto' on mobile screens, expecting it to work properly. It's functioning well in responsive mode on the web. However, it does not scroll on mobile devices. @media (max-width: 992px) { ...

Effective ways to manage extensive forms in Angular 2

I have a complex form in my application. What is the most effective way to collect data from this form and transmit it to the API using Angular 5? ...

React: Content has not been refreshed

MarketEvent.tsx module is a centralized controller: import * as React from 'react'; import EventList from './EventList'; import FullReduce from './FullReduce'; import './MarketEvent.less' export default class Mark ...

"Facing an issue where ts-node is not recognizing d.ts files, despite tsc being able to compile them

I am currently using typescript along with express and attempting to enhance the request object in express. Below is my server.ts file: import express, { Request, Response } from "express"; const app = express(); app.use(function(req: Request, res: Respo ...

The JSONP request failed with an error stating: ReferenceError: document is not defined

My internship project involves developing a mobile application based on the website www.claroline.net using Nativescript and Angular 2. I have successfully implemented the login function, allowing users to sign in to the app. Next, I need to integrate not ...

Typescript: Delay code execution until a function has completed running

I've encountered an issue with my code that involves calling a function. Here is the snippet of code in question: this.getAllOptions(questionID); console.log("++++++++++++++++++++++++++++++++"); console.log(this.result); The task of this function is ...

Prevent any angular text box from allowing just one special character

Hello, I am facing a requirement where I need to restrict users from inputting only one special character, which is ~. Below is the code snippet: <div class="form-input "> <input class="pass" [type]="'passw ...

Failed CORS request in Angular

I encountered an issue while attempting to connect to an external API (not owned by me), as I received a CORS error message (refer to screen 1). In an effort to resolve this, I added 'Access-Control-Allow-Origin': '*' to my headers, bu ...

I prefer the value to switch to false whenever I navigate to a new route and then return to the previous route, as the sidebar remains open

click here for image details view image description here Struggling to set the value as false when revisiting this site. Need assistance! Could someone lend a hand, please? ...

How can you establish the default value for a form from an Observable?

Check out my TypeScript component below export interface Product{ id?:string, name:string, price:string; quantity:string; tags:Tags[]; description:string; files: File[]; } product$:Observable<Product | undefined>; ngOnIn ...

Encountered an unexpected import token in Angular2 (SystemJS)

i am trying to find a solution for this issue in my Angular2 project. I encountered an error and need assistance: `"(SystemJS) Unexpected token import SyntaxError: Unexpected token import at Object.eval (http://....../app.module.js:14:25) at eval (h ...

The element 'commit' cannot be found within the property

I am facing an issue when transitioning from using Vuex in JavaScript to TypeScript. The error message Property 'commit' does not exist appears in Vuex's mutations: const mutations = { methodA (): none { this.commit('methodB' ...

Is there a way for Ionic to remember the last page for a few seconds before session expiry?

I have set the token for my application to expire after 30 minutes, and I have configured the 401/403 error handling as follows: // Handling 401 or 403 error async unauthorisedError() { const alert = await this.alertController.create({ header: 'Ses ...

Typescript's async function failing to execute properly

I'm currently facing an issue with my code and I'm a bit puzzled as to where the problem lies. The console is displaying the correct data for this.allNominations, but it appears that the third for-loop is not being executed at all. As a result, t ...

How can the creation of directories for services be avoided in angular-cli?

For those of us using angular-cli, starting from version 1.4, they made the decision to create separate directories not just for components (which is understandable) but also for services that only consist of 2 files: the service file and the test file. ...