角:返回ID从$ HTTP内部父函数 [英] Angular: Return id From $http Inside Parent Function

查看:136
本文介绍了角:返回ID从$ HTTP内部父函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如果我这样做的权利,但我有一个父函数 returnPersonId(),它使用 $ HTTP 来获取一个对象,并返回该对象的 ID

I'm not sure if I'm doing this right, but I've got a parent function returnPersonId() which uses $http to fetch an object and return that object's id.

function returnPersonId(n) {
  var q = 'http://api.themoviedb.org/3/search/person?api_key=' + apiKey + '&query=' + n;
  $http({ method: 'GET', url: q })
    .success(function (data, status, headers, config) {
      if (status == 200) {
        var person = data.results[0];
        var id = person.id;
        return id;
      }
    })
    .error(function (data, status, headers, config) {
      console.log('Error happened whilst getting the actor or actress.');
    })
}

目前它返回 ID 成功方法内。我不知道如何将 ID 返回到它的父函数,所以如果我运行的功能,我返回的ID,像这样:

Currently it's returning the id inside the success method. I'm not sure how to return the id to its parent function, so if I run the function I'm returned the id, like so:

returnPersonId('tom+hanks'); // returns 31

我怎么会去这样做?

How would I go about doing this?

任何帮助是AP preciated。

Any help is appreciated.

在此先感谢!

推荐答案

作为回调函数不返回从中你需要切换您的code风格来使用承诺模式的数据,你可以很容易地返回数据成功或失败。

As callback function doesn't return a data from it you need to switch your code style to use promise pattern where you can easily return a data on success or on failure.

function returnPersonId(n) {
  var q = 'http://api.themoviedb.org/3/search/person?api_key=' + apiKey + '&query=' + n;
  return $http({ method: 'GET', url: q })
    .then(function (resp) {
      var data = res.data
      if (res.status == 200) {
        var person = data.results[0];
        var id = person.id;
        return id;
      }
    },function (error) {
      console.log('Error happened whilst getting the actor or actress.');
      return 'Error occured'
    })
}

这篇关于角:返回ID从$ HTTP内部父函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆