gpt4 book ai didi

javascript - Angular : Access resource value in controller

转载 作者:数据小太阳 更新时间:2023-10-29 04:37:10 24 4
gpt4 key购买 nike

我不擅长 javascript,而且对 Angular 还是个新手,所以请多多包涵。

我的服务器返回这个:

{"latitude": 3.172398, "name": "Event", "longitude": 101.6739005}

services.js

var mapModule = angular.module('map.services', ['ngResource']);

mapModule.factory('Event', function($resource) {
return $resource('/custom_api/get_event_details/:eventId/',
{eventId: '@id'});
});

controller.js

function mapCtrl($scope, Event) {
var eventDetail = Event.get({eventId: $scope.eventId});
console.log(eventDetail);
console.log(eventDetail.latitude);
}

我正在尝试通过 eventDetail.latitude 访问我的服务器返回的 json,但我得到的是 undefined

在控制台中,console.log(eventDetail) 看起来像:

e {$get: function, $save: function, $query: function, $remove: function, $delete: function}
latitude: 3.172398
longitude: 101.6739005
name: "abc"
__proto__: e

我知道 eventDetail 是一个 resource 实例,但我如何直接获取值?

如果我在我的 Controller 中设置了 $scope.eventDetail,我将能够通过我的模板中的 {{ eventDetail.latitude }} 访问它。

我究竟该如何在 Controller 中执行此操作?

最佳答案

来自 the docs :

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data.

所以除非你把它放在回调函数中,否则你的日志记录不会工作,就像这样:

function mapCtrl($scope, Event) {
Event.get({eventId: $scope.eventId},function(eventDetail){
//on success callback function
console.log(eventDetail);
console.log(eventDetail.latitude);
});
}

如果您出于某种原因不想使用资源,您可以使用$http service :

$http.get(url).then(function(response){console.log(response.data);});

关于javascript - Angular : Access resource value in controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16196121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com