0

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)
  }
oudekaas
  • 325
  • 1
  • 6
  • 21
  • where are you trying to do `newService.getContentReplies(this.parentAuthor, this.parentPermlink)`? – AT82 Dec 22 '17 at 08:38
  • it is in the service, outside of oninit and constructor. Using => allows me to reach the this of the service, which fixed my issue. – oudekaas Dec 22 '17 at 13:49

1 Answers1

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)
 }
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • Thank you for your quick answer, I am now getting the message: parentPermLink is not a function. I am trying other formats as with => it does indeed seem I can reach the earlier instance. – oudekaas Dec 22 '17 at 01:34
  • sorry the format was wrong, check updated – Sajeetharan Dec 22 '17 at 01:35
  • 1
    did it work for you? – Sajeetharan Dec 22 '17 at 02:18
  • Yes Thank you so much Sajeetharan, you saved me a lot of time!!! I just couldn't see how to make this work. Could I trouble you for a question about observables? And how do I upvote you? – oudekaas Dec 22 '17 at 13:43
  • I am still working on my reputation, just started so I can't upvote yet, I tried though!! – oudekaas Dec 22 '17 at 14:08
  • I am having the same issue now but within the component, I am trying to use this.quill from outside the constructor/ Oninit in a method, like below however it also says getContents is not a property of undefined: public save(permlink) { var dilta = this.quill.getContents()} this.quill is set in another method in the same component via (onInit of the primeng-editor), but I have the same issue with trying to make use of this.newService in a method outside of the constructor/ onInit. This used to work but somehow not anymore. – oudekaas Dec 22 '17 at 19:38
  • Issue is solved, it took me some time to figure that within the component outside of constructor and onInit I have to use = () => for methods to have access to the this of the component. – oudekaas Dec 23 '17 at 00:53