angularjs发送get请求出现错误

后端有个接口,请求/api/avatar/这个网址时,返回一个图片的实际路径/static/images/uploads/default,在浏览器中测试是完全OK的,如图:

https://img2.mukewang.com/5c905f7b0001904603400210.jpg

但使用angular的get方法,代码如下:


var myapp = angular.module("myapp", []);

myapp.controller("MainCtrl", ["$http", function ($http) {

    var self = this;

    this.get_avatar = function () {

        $http({

            method: "GET",

            url: "/api/avatar/"

        }).then(function (value) {

            console.log(value.data);

            return value.data;

        }, function (reason) {

            console.log(reason);

        })

    };

}]);

在html中使用<img ng-src="{{ctrl.get_avatar()}}">去获取图片地址,此时一打开html,前端疯狂向后端发送get请求,如图:

https://img4.mukewang.com/5c905f8b0001127207670146.jpg

浏览器console中也不断地重复刷出错误,如图:

https://img.mukewang.com/5c905f8d000138d005190436.jpg

沧海一幻觉
浏览 770回答 1
1回答

PIPIONE

没写过ng, 你看一下这么处理对吗 ?你写的那个是返回一个promise 而不是函数结果var myapp = angular.module("myapp", []);myapp.controller("imgControl", ["$http", function ($http) {var self = this;&nbsp; &nbsp; $http({&nbsp; &nbsp; &nbsp; &nbsp; method: "GET",&nbsp; &nbsp; &nbsp; &nbsp; url: "/api/avatar/"&nbsp; &nbsp; }).then(function (value) {&nbsp; &nbsp; this.src = value.data&nbsp; &nbsp; }, function (reason) {&nbsp; &nbsp; &nbsp; &nbsp; console.log(reason);&nbsp; &nbsp; })}]);<div ng-controller="srcControl as src"><img ng-src="{{src.src}}"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript