在 Angular 组件模板和类中处理字符串文字的最佳实践

Bry*_*Gom 1 angular

处理作为错误或通知显示给客户端的消息字符串的最佳实践是什么,以便在打字稿方面和 htlm 中都没有硬代码?

例如,它发生在我身上:在 html 中:

<h1> {{header_message}} </h1>
Run Code Online (Sandbox Code Playgroud)

在打字稿中:

let notificationInfo: string = 'notifications.infoMessage';
Run Code Online (Sandbox Code Playgroud)

ulm*_*mas 5

Usually you would create some sort of a constants file for your messages (or any other strings for that matter, for example strings used in comparison expressions). You can have a single module-specific constants file, for example:

Declaration

constants/
  message.constants.ts
components/
  ...
notification.module.ts
Run Code Online (Sandbox Code Playgroud)

In that file you want to export a constant:

export const MESSAGES = {
  alerts: {
    success: 'Operation completed succesfully.',
    warning: 'Your changes may be lost.'
    },
  notification: {
    info: 'For your information...',
  },
  header: 'Alerts & Notifications'
}
Run Code Online (Sandbox Code Playgroud)

Usage

Then you can import this constants file into any of your components as needed:

import { MESSAGES } from '../constants/message.constants';
Run Code Online (Sandbox Code Playgroud)

And then in the component class itself, assign the import to a property:

class MessageNotification {
  messages = MESSAGES;
  notificationInfo = this.messages.notification.info;
}
Run Code Online (Sandbox Code Playgroud)

You can also access them in your template:

<h1> {{ messages.header }} </h1>
Run Code Online (Sandbox Code Playgroud)

Later as the number of messages grows, they can be refactored into multiple constants files grouped by feature, topic, kind etc.

Benefits

There are a few benefits of externalizing the string literals:

  1. Easier to update the messages since they are all in one place.
  2. Easier to review all messages at once for wording consitency.
  3. Translations: if you require multi-lingual features, with some adjustments, you can easily show strings depending on the language.
  4. Re-use: if the same message shows up in multiple places, you can re-use it instead of copying/pasting, and to update you only update one instance.