AngularJS1.5に再挑戦 その8 HTTP Request in Angular - $http
概要
AngularJS1.5に再挑戦 その8 HTTP Request in Angular - $http
参考動画・参考サイト
AngularJS — Superheroic JavaScript MVW Framework
AngularJS1.5に再挑戦 その8 HTTP Request in Angular - $http
[ {"title": "Some Title", "id":1, "description": "This is a book", "publishDate": "2017-01-08"}, {"title": "Title2", "id":2, "description": "This is a book"}, {"title": "Some Title3", "id":3, "description": "This is a book"}, {"title": "Some Title4", "id":4, "description": "This is a book"}, ]
上記はjson形式に合うように、文字列は、ダブルクオーテーションで囲ってある。
config.ruファイルのurlsに、"/json"を追記する。
blog-detail.component.jsに、posts.jsonを取得して、そのresponseをconsole.logに表示するというcomponentsのコードを追記する。
'use strict'; angular.module('blogDetail'). component('blogDetail', { templateUrl: '/templates/blog-detail.html', controller: function($location, $routeParams, $scope){ $scope.notFound = true $http.get("/json/posts.json").then(successCallback, errorCallback); function successCallback(response, status, config, statusText){ console.log(response) } function errorCallback(response, status, config, statusText){ console.log(response) } // notFoundがtrueの場合 if ($scope.notFound){ console.log("Not found") // change location。これには、$locationの継承が必要。 $location.path("/404") } } });
SyntaxErrorが出て、取得ができない。。。。これは、posts.jsonのリストの最後に、
,
が入っていたためぽい。それを削除して再度トライしたら成功した。consolelogを見ると以下のように表示される。これがresponseの中身。
Object { data: Array[4], status: 200, headers: fd/<(), config: Object, statusText: "OK " }
- 試しに、console.log(response.data)として、再度トライして見る。以下の通りの返し。
Array [ Object, Object, Object, Object ]
- 一つ一つのobjectは、以下のようにデータが格納されている。
description:"This is a book" id:4 title:"Some Title4"
- 最終的に以下のようにforEachで、DetailViewのそれぞれのアイテムを表示させる。
function successCallback(response, status, config, statusText){ $scope.notFound = true var blogItems = response.data $scope.posts = blogItems //ここで、responseのリストをcontextのpostsに代入する。 angular.forEach(blogItems, function(post){ if (post.id == $routeParams.id){ $scope.notFound = false $scope.post = post } }) } function errorCallback(response, status, config, statusText){ $scope.notFound = true console.log(response) } // notFoundがtrueの場合 if ($scope.notFound){ console.log("Not found") // change location。これには、$locationの継承が必要。 $location.path("/404") }
ポイントは、
$scope.notFound = true
を各functionごとに毎回定義していること。この理由はよくわからない。この辺は、参考書などで要復習だな。