Build a single service in Angular 6 that can be used by multiple components

My template header component has a service for translations stored in local storage. In the HTML, I use:

<p>{{trans('menu.items.news')}}</p>

I also have a method in header.component.ts:

 trans(key){

    const TRANS = JSON.parse(localStorage.getItem('translations'));

    return key.split('.').reduce(function(prev, curr){
      return prev ? prev[curr] :  null;
    }, TRANS || self);
  } 

However, I want this method to be accessible by other components in the root module, not just in the header component.

In addition, there is a service for fetching translations in the header's HTML select list:

changeTranslation(e){

    localStorage.setItem('language', e.target.value);

    localStorage.removeItem('translations');

    this.translation.getTranslation().subscribe(response => localStorage.setItem('translations', JSON.stringify(response)));
  }
 

How can I implement or call the translation service once in the app module so that it can be used in other components? Any suggestions would be appreciated. Thank you!

Answer №1

If you are looking to achieve this, consider using BehaviorSubject and refer to the following example for implementation:

Visit StackBlitz

Answer №2

If you want to utilize the trans method across various components, consider placing it within an Angular service. Then, utilize Dependency Injection (DI) to inject this service into any component where you would like to use the trans method.

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

Unleashing the Potential of TypeScript Union Types

My code consists of a union type called PromptOptions: type PromptOptions = | BasePromptOptions | BooleanPromptOptions | StringPromptOptions type BasePromptOptions = { kind: string | (() => string) }; type BooleanPromptOptions = { kind: ' ...

Enumerated types in Typescript: access the values

Below is a flagged enum I have: enum PermissionEnum { SU = 1 << 0, // 1 Administrator = 1 << 1, // 2 User = 1 << 2 // 4 } If the value given is 6, how can I achieve: An array of strings -> ['Adm ...

Tips for associating an identifier with a preexisting symbol in a TypeScript compiler transformer

Trying to implement a typescript compiler transform with the typescript compiler API has been challenging. Despite emitting new Identifier nodes to the final .js file, they appear to lack symbol binding information, resulting in incorrect output. For inst ...

Accessing form validation status of page 1 in Angular2 from page 2 - A simple guide

My current project utilizes Angular 4.2.x with two main pages: page 1 containing a form and page 2 serving as a summary page. Upon successful validation of all fields on page 1, I update a boolean flag in a shared service between the two pages. The expect ...

Utilizing dependency injection for nested services in Angular 2

I am designing a custom Broadcast system to create and utilize EventEmitters dynamically within the user context by injecting an EmitterService. @Injectable() export class BroadcastService implements OnInit { private _emitters: { [channel: string]: Ev ...

Custom React components are not designed to handle multiple onClick events simultaneously

One of my custom button components looks like this: export const Button = ({ children, onClick, className, ...props }: IButton) { const [selected, setSelected] = React.useState('primary') const handleSelected = () => { setSele ...

What is the best way to test a function that returns a JSX element in a unit test

I created a function that takes in a parameter and returns a JSX.Element //title.tsx export const getTitle = (pageTitle: string) => { return <title> {pageTitle} </title>; } This is how I am currently testing it: describe('Title c ...

Is there a way to compel Angular Universal to pre-render content sourced from an external api?

My goal is to utilize SSR in order to enhance the search engine optimization of my angular single page application. While I have successfully enabled SSR using Angular-Universal to serve static HTML, my components rely heavily on asynchronous API calls to ...

What is the maximum allowable size for scripts with the type text/json?

I have been attempting to load a JSON string within a script tag with the type text/json, which will be extracted in JavaScript using the script tag Id and converted into a JavaScript Object. In certain scenarios, when dealing with very large data sizes, ...

What is the best way to adjust the height of a dropdown box in an angular application?

Is there a way to change the height of the scroll view? It seems too long for my liking, any advice? I attempted to adjust it using css but unfortunately, it didn't work out. The scroll view appears excessively lengthy as shown in the image below. h ...

Node.js/Express API Endpoint Ceases Functioning

In my Angular/Express.js app, there is a post method within my api.service.ts file: post(data: any, endpointUrl: string): Observable<T> { console.log("REACHED POST METHOD") return this.http.post<T>(`${this.apiUrl}/${endpoint ...

When TypeScript tsc is unresponsive, there is no output or feedback provided

Just getting started with TypeScript! I've been working on transitioning my React.js project from JavaScript to TypeScript. I managed to resolve all the bugs and verified that it runs smoothly when using npm start. However, whenever I try to comp ...

Having difficulty implementing Bootstrap on a demo Angular project

I am currently working on an Angular Application and facing issues with loading styles properly. Below is the code I have: menubar.html: <header> <nav class="navbar navbar-expand-lg navbar-dark bg-dark" style="display: inline&q ...

Prevent the Mat Dialog from showing up depending on the situation

I am attempting to prevent a Mat Dialog from appearing unless a specific condition is met. I originally thought about using Angular Guard, but since there is no associated route with the component (besides the main webpage it's called from), that appr ...

Avoid performing linting on keys within tuples

Utilizing tuples-pairs in my application to define ordered-data with a label and contents makes it easier for me to comprehend compared to using an object structure like { label: string, contents: React.ReactNode }. While this method works efficiently, is ...

Steps for sending an email message to an email address added within our application:

In my Angular app, I have an "add" button that calls the handleSubmit function when clicked. This function adds the email to the email list of the app. I would like to send an email to the added email notifying them that their email has been added to our ...

How to retrieve various data points from a service and pass them to a component in

Utilizing an httpmodule to fetch data from the backend, I am faced with a challenge. While loading data in the service and returning it to the component, I also need to send a status code along with it. Unfortunately, the Data model is already set and cann ...

When using Next.js and Jest, an error may occur stating "Element type is invalid: expected a string or a class/function but got an object."

I am currently in the process of setting up unit tests for my Next.js project. I have carefully followed the guidelines provided in the official documentation on testing. The issue I'm encountering appears to be related to either the configuration it ...

Mapping imports in TypeScript refers to the process of linking external dependencies or modules

Imagine in the world of typescript, whenever I write an import statement like this import styles from "./styles.module.scss"; I want typescript to actually import this file ./styles.module.scss.json The reason for this is that a JSON object con ...

Can the inclusion of a type guard function impact the overall performance of the application?

const typeGuard = (param: any): param is SomeType => { return ( !!param && typeof param === "object" && param.someProperty1 !== null && param.someProperty2 === null ) } If a type guard function similar to the code above is exe ...