Rails を使用して JSON API を提供するアプリを作成しています。ngResource
これらの json エンドポイントを使用するために Angular モジュールを使用しています。
をngResource
正しく構成し (以下を参照)、その結果を$scope
変数に保存したり、コンソールにログアウトしたりできますが、サービスを使用してngResource
呼び出しを行い、その結果を通常の古いファイルに保存するのに苦労しています。array
変数。
この例でGenre
は、Rails JSON API にアクセスする というリソースがあります。GenreService
「 Genre.index Genre
() Array」変数を挿入して作成しようとしcall and store those results into a local
ます。
ファイルの内容は次のとおりです。
ジャンル.js.コーヒー
'use strict'
app = angular.module("ATWP")
app.factory "Genre", ($resource) ->
$resource "/genres/:slug",
slug: "@slug"
,
create:
method: "POST"
index:
method: "GET"
isArray: true
show:
method: "GET"
update:
method: "PUT"
books:
method: "GET"
ジャンルService.js.coffee
'use strict'
app = angular.module('ATWP')
genreService = app.factory 'GenreService', (Genre) ->
genreResponse = new Array()
Genre.index((response) ->
genreResponse = response
)
console.log 'Genre Response'
console.log genreResponse
getGenres: ->
genreResponse
genreResponse
この時点でログを記録すると、実際には配列が表示されます。ただし、GenreService
コントローラーに挿入してからその結果をGenreService.getGenres()
配列に格納すると、コンソールにログを記録するたびにその配列は空に見えます。
なぜそうなのか不思議です。Promise
APIを使用する必要がありますか? なぜこれが起こっているのかを理解するのを手伝ってくれる人はいますか?
みんなありがとう。