無法訪問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