Javascript Angular1.x ES6应用程序中的服务返回的对象赢得';模板中没有显示?
我试图通过使用ES6创建一个Angular 1.x应用程序来学习ES6。我试图检索一个配方对象数组并在模板中显示它们,但似乎无法让它们显示出来 以下是相关文件: app.jsJavascript Angular1.x ES6应用程序中的服务返回的对象赢得';模板中没有显示?,javascript,angularjs,ecmascript-6,Javascript,Angularjs,Ecmascript 6,我试图通过使用ES6创建一个Angular 1.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
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);
}
}
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}
{{$ctrl.name}
可以正常工作,但不能重复食谱和ng;我错过了什么?模板加载正确,我没有收到任何错误,并且正在从后端成功检索配方
我也愿意将检索从app.config.js中的
resolve
移动到recipes.controller.js中(如果需要的话)?即使服务已注入控制器中,解析对象也未被删除。此外,您还必须将其暴露在视图中。您需要在控制器中执行以下操作:
export default class RecipesCtrl {
constructor(RecipesService, recipes) {
'ngInject';
this.recipes = recipes;
this.name = 'Recipes';
}
}
我的服务返回一个未定义的对象;它需要的不是
res.data.recipes
,而是res.data
,似乎不起作用。即使我在路由器中去掉resolve并调用控制器中的服务,它也不会工作。