search

Home  >  Q&A  >  body text

javascript - es6 parameter injection problem

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;
为情所困为情所困2817 days ago464

reply all(2)I'll reply

  • 大家讲道理

    大家讲道理2017-05-19 10:28:27

    let a = new loginCtrl(http)

    You didn’t give http to the constructor

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-19 10:28:27

    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.

    reply
    0
  • Cancelreply