HTTP (Http)
اینجا درباره «HTTP در AngularJS» حرف می زنیم. سرویس $http درخواست می فرستد و پاسخ می گیرد. «درخواست (Request)» یعنی پیام به سرور. «پاسخ (Response)» یعنی جواب سرور. بنابراین با چند خط کد، داده را می خوانیم.
HTTP در AngularJS چیست؟
$http یک سرویس است. این سرویس داده دور را می خواند. سپس نتیجه را در اسکوپ می گذارد. اسکوپ (Scope) جایی برای متغیرهاست.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm").then(function(response) {
$scope.myWelcome = response.data;
});
});
میان بُرها و شیوه پیکربندی
متدهای کوتاه مثل get() و post() راحت اند. اما می توانیم شیء پیکربندی بدهیم. سپس موفقیت و خطا را جدا مدیریت کنیم.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http({
method: "GET",
url: "welcome.htm"
}).then(function mySuccess(response) {
$scope.myWelcome = response.data;
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
});
شناخت اجزای پاسخ
پاسخ شامل data و status و statusText است. بنابراین می توانیم وضعیت را نمایش دهیم.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm").then(function(response) {
$scope.content = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statusText;
});
});
مدیریت خطا با then
تابع دوم در then خطا را می گیرد. سپس پیام مناسب نشان بده.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("wrongfilename.htm").then(function(response) {
$scope.content = response.data;
}, function(response) {
$scope.content = "Something went wrong";
});
});
خواندن JSON و نمایش لیستی
JSON فرمت داده سبک است. با ng-repeat می چرخیم و آیتم ها را نشان می دهیم.
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in myData">{{ x.Name + ', ' + x.Country }}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("customers.php").then(function(response) {
$scope.myData = response.data.records;
});
});
<\/script>
گام های عملی
- یک ماژول و کنترلر بساز.
- سرویس $http را تزریق کن.
- درخواست بفرست و پاسخ بخوان.
- خطا را مدیریت و پیام بده.
نکته: برای آشنایی با سرویس ها به سرویس ها برو. همچنین لینک HTTP در AngularJS را برای مرور سریع نگه دار.
جمع بندی سریع
- $http درخواست می فرستد و پاسخ می گیرد.
- میان بُرها کار را ساده می کنند.
- پاسخ شامل داده و وضعیت است.
- خطا را همیشه مدیریت کن.
- JSON با ng-repeat عالی نمایش داده می شود.