[英]How to request API data with $http service
我正在使用Riot Games API开发应用程序,但此示例是使用REST国家API完成的 。 https://restcountries.eu/rest/v1/alpha/co
我使用MEAN.IO堆栈,这是我的代码:
test.html
<html ng-app="lolData">
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.indigo-pink.min.css">
<script defer src="https://code.getmdl.io/1.1.3/material.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<section id="center" ng-controller="summonerStats">
<form ng-submit="search()">
<div class="mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" type="text" id="summonerName" placeholder="Summoner Name">
<label class="mdl-textfield__label" for="sample1"></label>
</div>
<input class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" type="submit" value="Search"/>
<p ng-show="show">
{{ mystats.name }}
</p>
</form>
</section>
</body>
</html>
test.js
'use strict';
var lolData = angular.module('lolData', []);
console.log("before controller");
lolData.controller('summonerStats', function($scope, $http) {
var url = "https://restcountries.eu/rest/v1/alpha/co";
console.log("inside controller");
$scope.show = false;
$scope.search = function() {
$http.get(url)
.success(function(response) {
$scope.mystats = response;
$scope.show = true;
console.log("inside success controller");
});
};
});
当我刷新页面时,代码将执行到“控制器之前” console.log。 它无法进入lolData.controller。 并在浏览器控制台中显示以下错误。
而且html不接受嵌入的javascript范围。
我想念什么?
更新1:
我在代码笔中添加了index.html: Index.html
还有一个Codepen中的Header.html: header.html
不知道这是否是您的问题,但是$http.success
, $http.success
(和$http.error
)已贬值 。 而是使用回调函数来获取成功和错误
var url = "https://restcountries.eu/rest/v1/alpha/co";
$http.get(url).then(
function successCallback(response) {
$scope.mystats = response;
$scope.show = true;
console.log("inside success controller");
}, function errorCallback(error) {
console.log(error);
});
您的响应对象没有执行您认为的操作。
从angular的文档中,您可以看到响应具有附加到返回对象的多个属性。
你要
$scope.mystats = JSON.parse(response.data);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.