【问题标题】:Constant prefix for urlurl 的常量前缀
【发布时间】:2016-12-12 18:23:00
【问题描述】:

我正在尝试为 url 添加一个常量前缀,所以我做到了:

import angular from 'angular';
import Home from './home/home';
import Login from './login/login';

let componentModule = angular.module('app.components', [
  Home,
  Login
]).constant('apiv1', 'http://localhost:56202/api/')

.name;

export default componentModule;

然后,我在控制器中编写以下内容:

class LoginController {
  static $inject = ['$http'];   

  constructor($http) {
    this.$http = $http;
    this.name = 'login';
  }

  login(user) {
    console.log(user.name);
    console.log(user.password);
    this.$http.get(apiv1 + 'clients').then(function (response) {
     console.log(response.data);
    });
  }
}

export default LoginController;

但它给了我:

angular.js:14324 ReferenceError: apiv1 未定义在 LoginController.login

我试图将整个 url 放入控制器中并且它正在工作,但我想为我的应用程序操作一个特定的 url 前缀。

【问题讨论】:

    标签: javascript angularjs ecmascript-6


    【解决方案1】:

    以与注入 $http 相同的方式注入 apiv1 常量。请参阅角度 Dependency Injection 文档。

    class LoginController {
      static $inject = ['apiv1', '$http'];   
    
      constructor(apiv1, $http) {
        this.$http = $http;
        this.apiv1 = apiv1;
        this.name = 'login';
      }
    
      login(user) {
        console.log(user.name);
        console.log(user.password);
        this.$http.get(this.apiv1 + 'clients').then(function (response) {
         console.log(response.data);
        });
      }
    }

    【讨论】:

      【解决方案2】:

      要使用您已注册的常量(或服务、工厂、提供者等),您必须将其注入您的控制器。即将 apiv1 添加到控制器的构造函数中

      class LoginController {
        static $inject = ['$http', 'apiv1'];   
      
        constructor($http, apiv1) {
          this.$http = $http;
          this.apiv1 = apiv1;
          this.name = 'login';
        }
      
        login(user) {
          console.log(user.name);
          console.log(user.password);
          this.$http.get(this.apiv1 + 'clients').then(function (response) {
           console.log(response.data);
          });
        }
      }
      
      export default LoginController;
      

      【讨论】:

        【解决方案3】:

        请考虑角度依赖解析是遗留,意思是,它不有助于自动数据绑定和范围解析 - 它不应该被使用。由于您已经在使用 ES6,因此问题在于:

        /* your Config */
        export const API_V1 = 'http://localhost:56202/api/'
        /* your Controller */
        import { API_V1 } from 'your-config'
        /* your server call */
        $http.get(`${API_V1}clients`)
        

        这将避免多余的注入、代码噪音并简化您未来升级的道路。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-06-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-04
          • 1970-01-01
          相关资源
          最近更新 更多