2017-01-12 22 views
1

私がやっているのは、応答が完了した後に配列をいくつか追加することです。応答が完了したら何かをしますか?

this.$http.post('/blog/article/' + articleid + '/comment', article_comments) 
.then(function (response) { 
    self.comment_id = response.data.comments.id; 
    this.user = response.data.comments.user; 
    this.dataReady = true; 
    }, function (response) { 

}); 

if (this.dataReady == true) { 
    this.comments.push({ 
     comment: this.comment, 
     downvotes: 0, 
     upvotes: 0, 
     user:this.user, 
     date_ago: moment(Date.now()).fromNow() 
    }) 
    this.loadComments(); 
    console.log(this.comments); 
} 

がどのように私はこの問題を解決することができます:イムREPONSEの準備ができたが、成功せずにあるかどうかを確認しようとして ?私は応答からのデータが必要で配列をプッシュする必要があるため、応答が完了する前に配列をプッシュしようとするとエラーが発生します。

+0

あなたは約束をもっと使うことができます。応答を返すと、 '.then'を別の' .then(関数(応答){...})と連結することができます。これは、適切なロジックシーケンスでこれらの非同期呼び出しを行います – cassioscabral

答えて

1

あなたが方法で応答を取得した後に実行したい、次のコードを、置くことができます:updateOtherVarsを言う:

if(this.dataReady == true){ 
     this.comments.push({ 
      comment: this.comment, 
      downvotes: 0, 
      upvotes: 0, 
      user:this.user, 
      date_ago: moment(Date.now()).fromNow() 

      }) 
      this.loadComments(); 
       console.log(this.comments); 
     } 

をし、次のように、this.$httpブロックからこのメソッドを呼び出します。

this.$http.post('/blog/article/' + articleid + '/comment', article_comments).then(function(response){ 
      self.comment_id = response.data.comments.id; 
      this.user = response.data.comments.user; 
      this.dataReady = true; 
      this.updateOtherVars() //Call method from here 
     },function(response){ 

     }); 
+0

私はすべてを試したと私はそれを試してみません:Sのtnx男 – None

関連する問題