class loginCtrl { constructor(http) { [this.http, this.name] = [http, 'login']; } login() { console.log(this.http); console.log(this.name); } } loginCtrl.$inject = ['http']; let a = new loginCtrl(); a.login();
After calling this, http is undefined, but it can be printed out by clicking on the event.
What is going on? Angular is used for injecting http.
http code is as follows:
class http { constructor($http) { this.$http = $http; this.options = { headers: { 'Content-type': 'application/json;charset=utf-8', 'accessToken': 2332 } } } get(data, url, cb) { let gets = {method: 'GET', params: data, url: url} Object.assign(gets, this.options) this.$http(gets).then(function (data) { console.log('success'); cb(data); }) } } http.$inject = ['$http']; export default angular.module('http', []) .service('http', http) .name;
let a = new loginCtrl(http)
You didn’t give http to the constructor
Because you inject an asynchronous method and others are synchronous methods. The synchronous method will be executed from top to bottom, but where an asynchronous method is encountered, a new thread will be opened for execution, that is, the method you inject into http and your login method Parallel, run directly. After your login thread finishes running, the HTTP injection thread will print it out before it has time to return the value. But after adding the click event, an event triggering thread is opened. When an event is triggered, the thread will add the event to the end of the queue to be processed, so that after clicking, the value returned after http injection is received, which is probably so.