Angular Observable显示字符数组而非字符串问题求助
问题解决方案
前端核心问题修复
页面显示字符数组的直接原因是错误地对字符串调用了Object.values()。当welcome是字符串类型时,Object.values(welcome)会将字符串拆分为单个字符组成的数组,导致渲染时出现逗号分隔的字符序列。
修改ngOnInit中的代码,直接将接口响应结果赋值给this.welcome即可:
ngOnInit(){ this.getWelcome().subscribe( welcome=>{ this.welcome = welcome; // 移除Object.values()调用 } ); }
后端潜在问题修复
你的后端代码存在线程安全和异步执行顺序隐患:
- 使用静态变量
myMessage和myMessage1,多线程并发请求时会出现数据覆盖问题 welcome()方法会直接返回拼接结果,但此时异步线程可能还未完成配置文件读取,导致返回空字符串或不完整内容
建议改用CompletableFuture等待所有异步任务完成后再返回结果,修复后的后端代码示例:
import org.springframework.core.io.ClassPathResource; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.InputStream; import java.util.Properties; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; @RestController public class MessageController { @RequestMapping(path = "/welcome") public String welcome() throws ExecutionException, InterruptedException { // 异步读取英文配置 CompletableFuture<String> enFuture = CompletableFuture.supplyAsync(() -> { Properties properties = new Properties(); try (InputStream stream = new ClassPathResource("welcome_en.properties").getInputStream()) { properties.load(stream); return properties.getProperty("welcome"); } catch (Exception e) { e.printStackTrace(); return ""; } }); // 异步读取法文配置 CompletableFuture<String> frFuture = CompletableFuture.supplyAsync(() -> { Properties properties = new Properties(); try (InputStream stream = new ClassPathResource("welcome_fr.properties").getInputStream()) { properties.load(stream); return properties.getProperty("welcome"); } catch (Exception e) { e.printStackTrace(); return ""; } }); // 等待两个异步任务完成后拼接结果 String enMsg = enFuture.get(); String frMsg = frFuture.get(); String result = enMsg + ", " + frMsg; System.out.println(result); return result; } }
上述修改既保证了异步执行的正确性,又避免了线程安全问题,配合前端修复即可正常显示拼接后的字符串。
内容的提问来源于stack exchange,提问作者Johnny Rinaldo
相关产品推荐
相关产品推荐

