Can't get result data with $http angularjs

前端 未结 2 1656
北海茫月
北海茫月 2021-02-08 21:12

I\'m trying to use $http, but why it return null result?

angular.module(\'myApp\')
.factory(\'sender\', function($http) {
    var newData = null;
    $http.get(\         


        
2条回答
  •  天命终不由人
    2021-02-08 21:32

    This JavaScript code is asynchronous.

    console.log(newData)
    return newData
    

    Is executed before what inside success

    newData = data;
    console.log(newData)
    

    So at first time, the newData is null (you set it to be null)

    And when the http response is returned (inside the success), the newData gets its new value.

    This is very common in Javascript, you should do all your work inside the success.

提交回复
热议问题