[英]how to use Angular to call ajax and populate content from the return (after page has already rendered)
我是后端API开发人员,是AngularJS( 版本1 )的新手,这是我当前的工作所编写的内容。
该页面在<html>标记中具有ng-app="app"
,并且ng-controller="BaseController as baseCtrl"
,并且呈现得很好。
从这里开始,有一部分(当前是服务器端)内容需要由ajax进行后期渲染来调用,因为其来源不可靠,有时甚至很慢。 我已经编写了API URL来返回内容,例如
{"status":"OK","id":"feed-whatsnew","content":"Unreliable source!"}
我的问题是,如何使用Angular将上面的“内容”填充到<div id="feed-whatsnew"> .. <div class="content"></div>..</div>
位置,并且不隐藏feed-whatsnew
?
到目前为止,角度渲染对我来说还是有意义的,但是像这样的任何辅助过程仍然是不透明的。 我知道我将如何在jQuery中处理它,但是想要避免尝试简单地“模仿”一个库而不是真正实现Angular框架。
在angular中,您可以使用$http
-provider通过ajax调用外部API。 这是您将如何做的一个例子
app.controller('BaseController',['$http', function($http){
var vm = this;
vm.content = {};
vm.fetchContent = function(){
return $http.get('/my-api-endpoint').then(function(response){
vm.content = response.data;
}, function(response){
console.error('Failed calling /my-api-endpoint ', response);
});
};
// Initiallly load content
vm.fetchContent();
}]);
调用$http.get(..)
开始是对给定外部URL的异步调用,并返回称为Promise的内容 。 异步调用完成后,此Promise解析,该脚本使用then([callback])
执行传递给Promise的then([callback])
。 然后,此回调将在响应中传递的数据填充到控制器中的vm.content
变量。
您可以在angular文档中了解有关$http
提供程序的更多信息。
当您想将内容呈现在某个地方时,可以执行以下操作:
<span>{{baseCtrl.content}}</span>
尽管那部分内容很大程度上取决于您要呈现的内容。
您可能应该将fetchContent()
函数分成一个Angular服务,但这是一个完全不同的主题。
AngularJS附带了功能强大的$http
库来执行ajax。 请浏览相对简单的文档, 网址为https://www.w3schools.com/angular/angular_http.asp
这是合理的步骤
$http
as
分配将有所不同。 angular.module('app', []) .controller('BaseController', function($http) { var vm = this; vm.feed = null; _getDataFromServer(); function _getDataFromServer() { var req = { url: 'https://jsonplaceholder.typicode.com/posts/1', method: 'GET' //could be post/put etc //data: someJson -- if webservice need so }; $http(req) .then(function(response) { vm.feed = response.data; }).catch(function(err) { console.log('some error occured!', err); }); } });
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script> <div ng-app="app" ng-controller="BaseController as vm"> <p>Using $http</p> <div id="feed-whatsnew" ng-hide="!vm.feed"> <!-- use {{}} or ng-bind to bind the data --> <!-- use ng-hide to show/hide the content conditionally --> Title from Ajax Response: {{vm.feed.title}} <div class="content"> Content: <p ng-bind="vm.feed.body"></p> </div> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.