简体   繁体   中英

Constant prefix for url

I am trying to add a constant prefix for an url, so I did:

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;

Then, I write the following in the controller:

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;

But it gives me:

angular.js:14324 ReferenceError: apiv1 is not defined at LoginController.login

I tried to putting the entire url in the controller and it is working, but I want to manipulate a particular url prefix for my app.

Inject apiv1 constant in the same way you've injected $http . See angular Dependency Injection documentation.

 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); }); } } 

To use a constant (or service, factory, provider, etc.) you've registered you must inject it into your controller. ie add apiv1 to your controller's constructor

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;

Please consider that angular dependency resolution is legacy , meaning, that where it does not contribute to automatic data-binding and scope resolution - it should not be used. As you are already using ES6, it is a matter of:

/* 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`)

This will save from superfluous injections, code noise and ease your path to future upgrades.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM