从$ http.get获得响应后执行方法

时间:2017-06-20 08:57:13

标签: angularjs asynchronous

我想添加一个配置文件,如果它不存在,否则,我只会进行更新:

profileExists(id) {
    return this.$http.get('/profiles/' + id).then(response => {
            return response.data;
        });
}

submitProfile(profile) {
    if (!this.profileExists(profile.id)) {
        this.addProfile(profile);
    } else {
        this.updateProfile(profile);
    }
}

addProfile(profile) {
    return this.$http.post('/profiles', profile)
        .then(res => res.data)
        .catch(this.$http.fallback);
}

updateProfile(profile) {
    return this.$http.put('/profiles/' + profile.id)
        .then(res => res.data)
        .catch(this.$http.fallback);
}

此代码的问题在于submitProfile方法,this.addProfile(profile);profileExists(id)的返回语句之前执行...我很难操纵异步代码。在完成所有profileExists(id)方法后,我不知道如何执行代码。

我的第二个问题是为什么我们在this.$http.getthis.$http.put上发表回复声明?

感谢。

4 个答案:

答案 0 :(得分:2)

我认为你需要从profileExists()

成功回调你的addProfile()

试试这个。

profileExists(id) {
    return this.$http.get('/profiles/' + id).then(response => {
            if(!response.data){
                 this.addProfile(profile);
            }else{
                 this.updateProfile(profile);
            }
        });
}

或者

profileExists(id){
     return this.$http.get('/profiles/' + id);
}

submitProfile(profile) {
this.profileExists(profile.id).then(response => {
     if (!response.data) {
          this.addProfile(profile);
     } else {
        this.updateProfile(profile);
     }
   })

}

答案 1 :(得分:2)

当您的代码到达if子句时,profileExists尚未返回,因此评估为false。您可以更改代码以检入回调函数

submitProfile(profile) {
    this.profileExists(profile.id)
       .then(response => {
           if(!response.data){
               this.addProfile(profile);
           } else {
               this.updateProfile(profile);
           }
       })
}

答案 2 :(得分:1)

你可以这样做:

submitProfile(profile) {
    return this.profileExists(profile.id)
       .then(exists => {
           if(!exists){
               return this.addProfile(profile);
           } else {
               return this.updateProfile(profile);
           }
    })
}

我们在实际调用之前放置了返回,因为我们想要返回promise。因此,在执行此操作后,调用submitProfile的任何人都可以执行某些操作。像这样:

service.submitProfile(profile)
  .then(result => console.log('submit success'));

他们也可以在一个地方的所有代码中发现错误。

service.submitProfile(profile)
  .then(result => console.log('submit success'))
  .catch(err => console.error('Failed to submit',err);

答案 3 :(得分:0)

您需要设置async http true。尝试在配置中添加此行代码。

$httpProvider.useApplyAsync(true);