Angular 2 TypeScript模板调用函数报错:this.translate.get未定义
解决TypeError: Cannot read property 'get' of undefined的问题
这个错误确实是**this上下文丢失**导致的。当你把onRemoving函数作为回调传给<tag-input>的[onRemoving]属性时,函数执行时的this已经不再指向你的组件实例,自然就找不到translate服务了。下面给你两种常用的修复方案,还会顺便修正你代码里的另一个小问题:
方案1:用箭头函数定义回调(最推荐)
箭头函数会自动捕获当前组件的this上下文,不会出现指向偏移的问题。另外注意onRemoving需要返回一个Observable来告诉标签组件是否允许删除标签,你原来的代码没有返回值,这也需要补全:
// 用箭头函数定义onRemoving public onRemoving = (tag: any): Observable<boolean> => { return this.translate.get('confirmation_text').pipe( map((res: any) => { const confirmationText = res['confirmation_text']; // 弹出确认框,根据用户选择返回true(允许删除)或false(取消删除) return confirm(confirmationText); }) ); }
方案2:在构造函数中绑定this
如果你更习惯用普通函数,可以在组件构造函数里手动把onRemoving的this绑定到组件实例:
constructor(private translate: TranslateService) { // 手动绑定this,确保函数执行时指向组件实例 this.onRemoving = this.onRemoving.bind(this); } public onRemoving(tag: any): Observable<boolean> { return this.translate.get('confirmation_text').pipe( map((res: any) => { const confirmationText = res['confirmation_text']; return confirm(confirmationText); }) ); }
额外提醒
你原来的代码里subscribe了翻译服务,但没有处理返回值的逻辑。这里改用pipe+map操作符,既可以获取翻译后的文本,又能直接返回组件需要的Observable<boolean>,符合tag-input组件对onRemoving的要求。
内容的提问来源于stack exchange,提问作者Jessie
相关产品推荐
相关产品推荐

