$resource 成功回调返回 $promise

Eri*_*son 3 promise angularjs angular-resource

使用 Angular 1.2.14,$resource 的成功回调应该返回一个对象,但它有时会得到一个 $promise。node/express Web 服务返回 null,但 Angular 将其解释为 $promise。当 Web 服务返回非空值时,成功回调按预期获取对象。

$resource('/api/users/:userId/team').get({ userId: userId }, function(team) {
    console.log('team: ', team);                
}, function(err) {
    console.log('err: ', err);
});
Run Code Online (Sandbox Code Playgroud)

team(成功回调的参数)的值是:

$promise: Object
    catch: function (callback) {
    finally: function (callback) {
    then: function (callback, errback, progressback) {
    __proto__: Object
    $resolved: true
__proto__: Resource
    $delete: function (params, success, error) {
    $get: function (params, success, error) {
    $query: function (params, success, error) {
    $remove: function (params, success, error) {
    $save: function (params, success, error) {
    constructor: function Resource(value) {
    __proto__: Object
Run Code Online (Sandbox Code Playgroud)

为什么成功回调得到的是 $promise 而不是对象?

Ben*_*aum 5

为什么成功回调得到的是 $promise 而不是对象?

因为它发出了一个成功的 HTTP 请求并收到了一个恰好是null. 返回null不是我们向 HTTP 服务器发出我们的值无效的信号 - 相反,我们返回适当的状态代码以指示失败 - 请参阅本文

我如何从客户端修复它?

好吧,你没有问这个,但我认为这是你真正关心的,因为$resource返回一个承诺,你可以自己转换它,例如通过装饰器。

如果您不需要可重用性,您可以简单地执行以下操作:

$resource('/api/users/:userId/team').get({ userId: userId }).then(function(res){
    if(res === null) return $q.reject("Error, server returned null");
    return res;
}).then(function(team) {
    console.log('team: ', team);                
}, function(err) {
    console.log('err: ', err);
});
Run Code Online (Sandbox Code Playgroud)

否则,您可以用更通用的方法包装它:

function notNull(prom){
    return prom.then(function(res){
        if(res === null) return $q.reject("Error, got null);
        return res;
    });
};
Run Code Online (Sandbox Code Playgroud)

这会让你做:

notNull($resource('/api/users/:userId/team').get({ userId: userId })).then(function(res){
      // server returned not null.
}).catch(function(e){
     // returned null, or other server error, or error in previous then handler.
});
Run Code Online (Sandbox Code Playgroud)