无法访问Angulars $ resource返回的属性

[英]Cant access properties returned by Angulars $resource


Im trying to fetch data with angulars resource factory, but I don't quite understand how to process the responce properly.

我试图用angulars资源工厂获取数据,但我不太明白如何正确处理响应。

The factory:

function dataFactory($resource, ENV) {
  return $resource('http://foo/bar', {
      accountId: '@accountId'
    },
    {
      getData: {
        method: 'POST',
         url: 'http://foo/bar',
         headers: {
            'Content-Type': 'application/json'
        }

      }
    }
  );
}

In the service:

在服务中:

     function fetchRealTimeData() {
        return dataFactory.getData(requestParameters).$promise;

  }

In my directive:

在我的指令中:

dataToApply = CdnAnalyticsService.fetchRealTimeData()

When I log dataToApply, I get this:

当我记录dataToApply时,我得到了这个:

screenshot

I can't use regular object notation to access the properties,returns undefined.

我不能使用常规对象表示法来访问属性,返回undefined。

How can I access the properties on the returned object?

如何访问返回对象的属性?

1 个解决方案

#1


0  

Your resource is returning a promise. You need to resolve that promise to access the returned data.

您的资源正在返回一个承诺。您需要解析该承诺才能访问返回的数据。

function fetchRealTimeData () {
  return dataFactory.getData(requestParameters)
    .then(function (data) {
      return data;
    });
}

The way that you're doing it, you're returning the actual promise object, not the resolved data from the promise. The reason you can see the data in the console is because it's resolved by the time that it logs out, but when you try to access it with dot notation, the promise still hasn't resolved and you get undefined.

你正在这样做,你将返回实际的promise对象,而不是promise中已解析的数据。您可以在控制台中查看数据的原因是因为它在注销时已经解决,但是当您尝试使用点表示法访问它时,承诺仍未解决且您未定义。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/08/15/a8270085c303fbd765e1a6fb2837272.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com