处理作为错误或通知显示给客户端的消息字符串的最佳实践是什么,以便在打字稿方面和 htlm 中都没有硬代码?
例如,它发生在我身上:在 html 中:
<h1> {{header_message}} </h1>
Run Code Online (Sandbox Code Playgroud)
在打字稿中:
let notificationInfo: string = 'notifications.infoMessage';
Run Code Online (Sandbox Code Playgroud)
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:
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)
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.
There are a few benefits of externalizing the string literals:
| 归档时间: |
|
| 查看次数: |
960 次 |
| 最近记录: |