angular 4 service cannot read property 'newSer

2019-06-11 23:42发布

问题:

This question already has an answer here:

  • How to access the correct `this` inside a callback? 10 answers

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