2017-04-12 8 views
0

私はES6を使ってAngular 1.xアプリを作ってES6を学びたいと思っています。レシピオブジェクトの配列を取得してテンプレートに表示しようとしていますが、表示されないようです。Angular1.xでサービスによって返されるオブジェクトES6アプリケーションはテンプレートに表示されませんか?

app.js

import angular from 'angular'; 
import uiRouter from 'angular-ui-router'; 

// Import app config file 
import Config from './config/app.config'; 

// Import templates file 
import './config/app.templates'; 

// Import functionality 
import './recipes'; 

// Create application 
angular.module('recipeApp', [ 
    uiRouter, 
    'templates', 
    'helloTech.recipes' 
]) 

angular.module('recipeApp').config(Config); 

app.config.js

function Config($stateProvider, $urlRouterProvider, $locationProvider) { 
    'ngInject'; 

    $locationProvider.html5Mode(true); 

    $stateProvider 
    .state('home', { 
     url: '/', 
     controller: 'RecipesCtrl', 
     controllerAs: '$ctrl', 
     templateUrl: 'recipes/recipes.html', 
     title: 'Recipes', 
     resolve: { 
     recipes: function(RecipesService, $state) { 
      return RecipesService.getAll().then(
      (recipes) => recipes, 
      (err) => $state.go('home') 
     ) 
     } 
     } 
    }); 
} 

export default Config; 

recipes.service.js

export default class RecipesService { 
    constructor($http) { 
    'ngInject'; 

    this._$http = $http; 
    } 

    getAll() { 
    return this._$http({ 
     url: 'http://localhost:5000/api/recipes/all', 
     method: 'GET', 
    }).then((res) => res.data.recipes); 
    } 
} 

レシピ:ここ

は、関連するファイルです。 controller.js

export default class RecipesCtrl { 
    constructor(RecipesService) { 
    'ngInject'; 

    this.name = 'Recipes'; 
    } 
} 

recipes.html

<section class="recipes-list"> 
    <h1>Recipes</h1> 
    <p>{{ $ctrl.name }}</p> 

    <div class="recipe-card" ng-repeat="recipe in $ctrl.recipes"> 
    <h2 ng-bind="recipe.name"></h2> 
    </div> 

</section> 

{{ $ctrl.name }}が正常に動作しますが、ないレシピとngのリピート;私はここで何が欠けているのですか?テンプレートが正しくロードされていて、エラーが発生せず、レシピがバックエンドから正常に取得されています。

また、app.config.js内のresolveと、必要な場合はrecipes.controller.jsから取り出しを移動することもできます。

答えて

0

サービスがコントローラに注入されているにもかかわらず、解決されたオブジェクトが存在しませんでした。あなたはビューにそれを公開する必要があります。あなたのコントローラのような何かをする必要があります:

export default class RecipesCtrl { 
    constructor(RecipesService, recipes) { 
    'ngInject'; 
    this.recipes = recipes; 
    this.name = 'Recipes'; 
    } 
} 
+0

これは動作していないようです。私がルータでの解決を取り除いて、コントローラ内のサービスを呼び出すときでさえ、それはどちらも動作しません。 –

0

私のサービスは未定義のオブジェクトを返していました。 res.data.recipesの代わりに、それはちょうどres.dataである必要がありました。

関連する問題