简体   繁体   English

角$资源

[英]Angular $resource

I am using the following pattern for my REST API , but vm.listing in my controller is always undefined ? 我正在为REST API使用以下模式,但是控制器中的vm.listing始终undefined Probably my pattern is not right? 我的模式可能不正确吗? Is there a different pattern to use here? 在这里可以使用其他模式吗? I don't want to call the .get(..) in my controller code. 我不想在控制器代码中调用.get(..)

    .factory("listingsResource", ["$resource", "$q", 'appSettings',
        function ($resource, $q, appSettings) {

            return $resource(appSettings.serverPath + "api/Listings/:id")

        }]);

    .factory("editService",
              var _listing; 
              var _getListing = function (listingId) {

                _listing = listingsResource.get({
                    id: listingId
                });
              }   

      return {
        listing: _listing,
        getListing: _getListing
    };

Controller Code: 控制器代码:

 createService.getListing(listingId);
 vm.listing = createService.listing;

The problem is that when you call listingsResource.get() it returns a promise. 问题在于,当您调用listingsResource.get()时,它将返回一个promise。 Not the data response. 不是数据响应。

You have to pass the get() a success callback and then set the listing variable inside this callback. 您必须将成功回调传递给get(),然后在此回调中设置列表变量。 I would do something like this: 我会做这样的事情:

    .service("listingsService", ["$resource", "$q", 'appSettings',
        function ($resource, $q, appSettings) {
            var _this = this;

            _this.listing = {};

            var listingResource = $resource(appSettings.serverPath + "api/Listings/:id");

            this.getListing = function(listingId){
                listingResource.get({id: listingId}, 
                    function (data) {
                        // Success callback
                        // Set listing keys-value pairs
                        // do not do: _this.listing = data
                        _this.listing.id = data.id;
                        _this.listing.title = data.title;
                    },
                    function(err) {
                        // error callback
                        console.log(err);
                    }
                )
            }
        }
    ])

This works fine with a factory aswell if you prefer. 如果您愿意,也可以在工厂中正常使用。 Then in the controller: 然后在控制器中:

 listingService.getListing(listingId);
 vm.listing = listingService.listing;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM