我有来自API的文章。当我转到http://localhost:60367/api/article/时,我的API会正确列出它们,并且当我转到http://localhost:60367/api/article/1
时,我会正确地为单个项目获取正确的数据使用angular,如何通过它的id获取其中一篇文章的数据,这样如果我转到我的角度应用程序并点击http://localhost:60300/perspectives/1/,我就会获得该项目的数据。 (fyi,当我转到索引http://localhost:60300/perspectives/时,我会相应地得到数据。)
请协助,我的app.js文件如下:
var url = "http://localhost:60367/api/article";
var modules = ['ngRoute', 'ngSanitize'];
var App = angular.module("App", modules);
// Route providers
App.config(function ($routeProvider, $locationProvider) {
$routeProvider
// Get route for perspectives homepage
.when('/', {templateUrl: 'partials/articles-home.html',
controller: ArticleController})
// Get route for perspectives single page
.when("/:id/", {templateUrl: 'partials/articles-single.html',
controller: ArticleController})
.otherwise({ redirectTo : "/"})
// Use the HTML5 History API
$locationProvider.html5Mode({ enabled: true, requireBase: false});
});
// Controller
var ArticleController = function ($scope, $http, $log) {
// For onsuccess, also do console.log for $log property
var onSuccess = function (response) {$scope.articles = response.data;
$log.info(response);};
var onFailure = function (reason) {$scope.error =
reason;$log.info(reason);};
// Get all students and display them in index
var getAllArticles = function () {$http.get(url).then(onSuccess,
onFailure)};
getAllArticles();
// Get single student by Id
//
//
};
App.controller("ArticleController", ArticleController);
解决方案:
好的,这就是我解决它的方法,我为单个项目创建了一个新的控制器,并像这样手动编写:
var SingleArticleController = function ($scope, $http, $routeParams) {
$http({
url: "http://localhost:60367/api/article/{id}",
params: { id: $routeParams.id },
method: "get"
})
.then(function (response) {
$scope.article = response.data;
});
};
答案 0 :(得分:1)
您想要使用$routeParams:
我在此处概述的内容将允许您在此处使用与您在配置中显示的相同的控制器。通常,您在路线中指定一个单独的控制器(类似
ArticleController
,ArticleListController
。)。如果您这样做,则适用相同的流程,但您无需检查是否有ID
参数。
在您的控制器中:
// Add $routeParams
.controller('ArticleController', function($scope, $routeParams) {
// Get the id
var id = $routeParams.id;
// Set url based on whether or not you have an ID
var fullUrl = id ? url + '/' + id : url;
var getAllArticles = function() {
$http.get(fullUrl).then(onSuccess,
onFailure)
};
})