angular 4 service cannot read property 'newService' of undefined [duplicate]

爱⌒轻易说出口 提交于 2019-12-10 12:14:54

问题


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

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

newService.service.ts

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

回答1:


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)
 }


来源:https://stackoverflow.com/questions/47934718/angular-4-service-cannot-read-property-newservice-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!