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

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

问题描述

我想追加的查询参数这是我从网址获取所有的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});
})

本作品第一次被用于邮政服务,但它注入它已经被初始化,并使用即使URL已经改变了第一个客户ID的第二次。

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的值作为PARAMS服务的函数调用。

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.

在code可能是这样的:

The code may like this:

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天全站免登陆