angularjsroute-provider

Passing an object from route to Controller via Route Provider resolve


I am trying to pass a variable from the resolve method of the $routeProvider to the controller that would be used for this route. but what happens is the object is being resolved but the controller does not wait till the resolution of the object. here is a snippet from the code i am using:

app.config(["$locationProvider", "$routeProvider", "$httpProvider", function ($locationProvider, $routeProvider, $httpProvider) {
        $locationProvider.hashPrefix('');
  .when("/EditProduct/:id",
            {
                templateUrl: "App/Products/editProductView.html",
                controller: "EditProductCtrl as vm",
                resolve: {

                    product: function (productsResource, $route, $routeParams) {
                        console.log($route.current.params.id);
                        return productsResource.getProductById().get({ id: $route.current.params.id }, function (data) {
                            console.log("inside the resolved function");
                            console.log(data.Name);
                            return data;
                        })
                    }
                }
            })
            .otherwise({ redirectTo: "/" });

so the log message with the name from the app.js statement is shown. while the controller has the supposedly resolved product injected as follows:

(function () {
    "use strict";
    angular.module("ProductManagementTool").controller("EditProductCtrl", ["product","productsResource", "currentUser", EditUserCtrl]);

    function EditProductCtrl(product, productsResource, currentUser) {
        var editCtrlViewModel = this;
        console.log("the full name is " + product.Name);
            editCtrlViewModel.product = product;
            editCtrlViewModel.title = "Edit: " + product.Name;


    }
}());

while the log message in the controller is shown as undefined.

i am using angular js 1.6.1 .


Solution

  • Controller won't wait, cause resolved element is a Promise returned by $resource (I presume you use $resource). You should make something like this:

    var editCtrlViewModel = this;
    product.$promise.then(function (element) {
        editCtrlViewModel.product = element;
        editCtrlViewModel.title = "Edit: " + element.Name;
    })