我正在使用 Riot Games API 开发一个应用程序,但这个示例是使用 REST Countries API 完成的。 。 https://restcountries.eu/rest/v1/alpha/co
我使用 MEAN.IO 堆栈,这是我的代码:
测试.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>
测试.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");
});
};
});
当我刷新页面时,代码将被执行,直到“在 Controller 之前”console.log。它无法进入 lolData.controller 内部。并在浏览器控制台中显示以下错误。
并且 html 不接受嵌入的 javascript 范围。
我错过了什么?
更新1:
我在codepen中添加了index.html:Index.html
还有 codepen 中的 Header.html:header.html
最佳答案
不确定这是否是您的问题,但$http.success
(和$http.error
)已depreciated自 v1.4.4 起。相反,使用成功和错误的回调函数
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);
});
关于javascript - 如何使用 $http 服务请求 API 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36218746/