Angular 4服务无法读取未定义的属性"newService" [英] angular 4 service cannot read property 'newService' of undefined

查看:72
本文介绍了Angular 4服务无法读取未定义的属性"newService"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在newService中调用一个方法,在该方法中我想调用方法changeMes​​sage.问题在于,在newService.getContentReplies中,this.newService没有引用NewService的实例,因此它无法读取其属性.我该怎么做才能使这项工作成功?

I am calling a method in newService and in that method I want to call the method changeMessage. The problem is that in newService.getContentReplies this.newService does not refer to an instance of NewService so it can't read the property of it. What can I do to make this work?

component.ts

component.ts

  newService.getContentReplies(this.parentAuthor, this.parentPermlink) 

newService.service.ts

newService.service.ts

 getContentReplies(parentAuthor, parentPermlink){
  steem.api.getContentReplies(parentAuthor, parentPermlink, function(err, 
   result) {
    this.newService.changeMessage(result)
  }

推荐答案

您需要使用箭头功能,此属性不会被覆盖,并且仍引用较早的实例.

You need to use arrow function, the this property is not overwritten and still references the earlier instance.

 getContentReplies(parentAuthor, parentPermlink){
  steem.api.getContentReplies(parentAuthor, parentPermlink) => ((result) { 
    this.newService.changeMessage(result)
 }

这篇关于Angular 4服务无法读取未定义的属性"newService"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆