在服务中使用 $routeParams [英] Use $routeParams in service

查看:19
本文介绍了在服务中使用 $routeParams的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将查询参数附加到我从 URL 获取的所有 API 调用中.

I'm trying to append a query parameter to all API calls which I fetch from the URL.

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

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

This works the first time the Post service is used but the second time it's injected it has already been initialized and is using the first customer ID even though the URL has changed.

我如何使这项工作按预期工作?

How do I make this work as intended?

推荐答案

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

Because services are singletons. That's why you get that behavior.

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

I recommend that do not inject $routeParams as the init params of a service. Instead, inject it in controllers, then call service's functions using the values in $routeParams as params.

代码可能是这样的:

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

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

这篇关于在服务中使用 $routeParams的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆