[英]Monolithic JHipster React Front End Application Properties
我正在使用 React 构建一个 JHipster Monolithic 应用程序。 在后端,我可以使用 application.yml / ApplicationProperties.java 添加可能在环境(Dev、Prod 等)之间更改的属性(例如 API 键)。
我的问题是,我可以在 React 前端做同样的事情吗? 这是一个 Spring 应用程序,因此相同的 application.yml 和 ApplicationProperties.java 就位。 有没有人有将自定义属性呈现到 UI 的代码示例?
我已经阅读了这篇文章的答案( JHipster React Front End (Gateway) Application Properties ),但它对我没有帮助,因为在我的情况下它是一个单一的应用程序。
另一篇文章中的解决方案适用于单体。 有关完整的解决方案,请参见下文:
首先,确保您已经配置了要公开的配置。 还要在ApplicationProperties.java
中配置它(或将ignoreUnknownFields
设置为false
):
application:
my-value: 'TestValue'
创建一个 REST 端点,用于向客户端公开配置值(从其他答案修改):
package com.mycompany.myapp.web.rest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Resource to return custom config
*/
@RestController
@RequestMapping("/api")
public class CustomConfigResource {
@Value("${application.my-value:}")
private String myValue;
@GetMapping("/custom-config")
public CustomConfigVM getCustomConfig() {
return new CustomConfigVM(myValue);
}
class CustomConfigVM {
private String myValue;
CustomConfigVM(String myValue) {
this.myValue = myValue;
}
public String getMyValue() {
return myValue;
}
public void setMyValue(String myValue) {
this.myValue = myValue;
}
}
}
创建一个reducer来获取和存储信息:
import axios from 'axios';
import { SUCCESS } from 'app/shared/reducers/action-type.util';
export const ACTION_TYPES = {
GET_CONFIG: 'customConfig/GET_CONFIG',
};
const initialState = {
myValue: '',
};
export type CustomConfigState = Readonly<typeof initialState>;
export default (state: CustomConfigState = initialState, action): CustomConfigState => {
switch (action.type) {
case SUCCESS(ACTION_TYPES.GET_CONFIG): {
const { data } = action.payload;
return {
...state,
myValue: data['myValue'],
};
}
default:
return state;
}
};
export const getConfig = () => ({
type: ACTION_TYPES.GET_CONFIG,
payload: axios.get('api/custom-config'),
});
最后,从组件调用 reducer 的getConfig
方法,例如在App.tsx
中:
import { getConfig } from 'app/shared/reducers/custom-config';
...
useEffect(() => {
props.getConfig();
}, []);
...
const mapDispatchToProps = { getConfig };
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.