angularjs – 在服务中使用$routeParams

前端之家收集整理的这篇文章主要介绍了angularjs – 在服务中使用$routeParams前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试将查询参数附加到我从URL获取的所有API调用.

factory('Post',function ($resource,$routeParams) {
    return $resource('api/posts',{customer_id: $routeParams.customerId});
})

这在第一次使用Post服务时工作,但第二次注入时它已经初始化并且正在使用第一个客户ID,即使URL已经更改.

我该如何按预期工作?

解决方法

因为服务是单身人士.
这就是你得到这种行为的原因.

我建议不要将$routeParams作为服务的init参数注入.
相反,将其注入控制器,然后使用$routeParams中的值作为参数调用服务的函数.

代码可能是这样的:

factory('Post',function ($resource) {
    return {
        doPost: function(customerId) {
            $resource('api/posts',{customer_id: customerId});
        }
    };
});

//...
//in some controller
Post.doPost($routeParams.customerId)

猜你在找的Angularjs相关文章