TypeScript类私有变量赋值后弹窗消息未渲染模板ID值问题排查
问题原因
你的问题核心是模板字符串的求值时机:
类的实例属性会在实例初始化阶段完成赋值,你定义inuseItemMessage时使用的模板字符串插值${this.templatIds},会在初始化阶段就完成计算,此时this.templatIds还是初始的空字符串,所以inuseItemMessage的内容会直接固定为没有ID的版本,后续你修改this.templatIds也不会更新已经生成好的字符串。
同时你在回调中直接使用inuseItemMessage而非this.inuseItemMessage,也会导致无法正确读取类的私有属性。
修复方案
- 方案1:将固定属性改为动态getter,每次取值时实时拼接字符串
export class AgentsGridComponent implements AfterViewInit { private templatIds = ""; // 改成getter,每次访问时才用最新的templatIds拼接 private get inuseItemMessage() { return `This Agent is being used by Templates ${this.templatIds} and can't be archived` } // ...其他逻辑 this.agentsService.inuseTemplateAgentList(data.item.Id) .then((response) => { console.log(response.Value); this.templatIds = response.Value; // 加this访问类属性,此时getter会用最新的ID拼接 this.notificationManager.error(this.inuseItemMessage); }); }
- 方案2:直接在请求回调中拼接消息,不需要提前定义类属性
export class AgentsGridComponent implements AfterViewInit { // 不需要提前定义inuseItemMessage属性 private templatIds = ""; // ...其他逻辑 this.agentsService.inuseTemplateAgentList(data.item.Id) .then((response) => { console.log(response.Value); const inuseItemMessage = `This Agent is being used by Templates ${response.Value} and can't be archived` this.notificationManager.error(inuseItemMessage); }); }
内容的提问来源于stack exchange,提问作者Jefferson
相关产品推荐
相关产品推荐

