【问题标题】:Changing the URL/IP of AngularJS ngresource in Ionic在 Ionic 中更改 AngularJS ngresource 的 URL/IP
【发布时间】:2015-06-06 10:58:42
【问题描述】:

我想使用用户选择的IP地址多次更改REST URL,它可能有多个服务器IP地址,但是在应用程序启动后立即加载工厂文件后,IP地址(@ 987654321@) 无法更改。

有什么办法可以再次更改路径吗?

附: console.log($rootScope.baseURL) 可以成功输出值,但是返回部分后就不行了。

控制器:

$scope.authenticateUser = function(){
      $rootScope.$broadcast('ipChanged', $scope.user.ip);
}

工厂:

.factory( 'Models', function ($rootScope, $resource, Constants) {

        $rootScope.$on('ipChanged', function(event, data) {
            $rootScope.baseURL = "http://" + data + "/rest"
            console.log("$rootScope.baseURL")
        });

     return{
            appMaster_user_session: $resource($rootScope.baseURL + '/user/session',
                {
                    app_name: Constants.API.appName
                },
                {
                    'post': {method:'POST'},
                    'put': {method: 'PUT'}
                }
            ),

【问题讨论】:

    标签: angularjs ionic-framework resources factory ngresource


    【解决方案1】:

    使用 ngresource 操作中的 URL 参数解决了这个问题,它可以在启动 ngresource 后覆盖旧值。

    【讨论】:

      【解决方案2】:

      您可以使用provider recipe 使服务可配置。

      myApp.provider('Models', function ModelsProvider() {
        var apiUrl = 'http://www.deafault.com';
      
        this.apiUrl = function(value) {
          apiUrl = value;
        };
      
        this.$get = [function modelsFactory() {
          return {
              appMaster_user_session: $resource(apiUrl  + '/user/session',
                  {
                      app_name: Constants.API.appName
                  },
                  {
                      'post': {method:'POST'},
                      'put': {method: 'PUT'}
                  }
              )
           }
        }];
      });
      

      您需要在模块的配置部分设置 apiUrl。

      如果你想每次都获取不同的 url,你可以让这个资源包含一个接收 apiUrl 的函数。

      myApp.provider('Models', function ModelsProvider() { 
        this.$get = [function modelsFactory() {
          return {
              getSessionResource: function(apiUrl) {
                return $resource(apiUrl  + '/user/session',
                  {
                      app_name: Constants.API.appName
                  },
                  {
                      'post': {method:'POST'},
                      'put': {method: 'PUT'}
                  }
              )
           }
        }];
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        • 2017-10-01
        • 2017-04-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多