Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Angular

Easy way to maintain all message in one place angular

Manage your angular application messages in one place which out specifying those in different files

Managing log messages, toaster messages in the Angular application becomes hard if you define those messages in each and every file. Let’s say suddenly someone decides to change one particular message which is used in 100 components, you have to change all of those ones by one.

Therefore there should be a way to manage those in a single place.

To get started, let’s create a file called string under the assets folder. inside that create a messages.ts file.

In that file, we can use the following format to specify each message under a success, error, warning and info category. Also, we can group those with general messages and component-level messages.

export const generalMessages  = {
  success:{
    savedSuccessfully:'Successfully saved'
  },
  error:{
    saveError: 'Save error'
  }
}

export const userPageMessages  = {
    success:{
        userSavedSuccessfully:'user saved successfully'
    },
  }

Now we can import that file into each and every component which we need to use that message.

When we are importing that file we need to specify the relative path in each component. It sometimes becomes frustrating because the path will be changed based on the folder structure.

As a solution for that, we can use the tsConfig.json file to specify the path and we can define a path prefix which we can use in other files.

Open the tsConfig.json file and under the compilerOptions add the paths property. Under that, you can specify the path to our string folder.

tsConfig.json

"compilerOptions":{
	....,
	"paths": {
      "@messages/*": ["src/assets/string/messages"],
    }
} 

Now in the component, we can import that file like @messages/messages and use the values in their

import { generalMessages,userPageMessages } from '@messages/messages'

console.log(generalMessages.success.savedSuccessfully)