在angularJS中通过ID获取单品数据

Get single item data by ID in angular JS

我有文章来自 API。当我转到 http://localhost:60367/api/article/ and gets the correct data correctly for a single item when i go to http://localhost:60367/api/article/1

时,我的 API 正确列出了它们

使用 angular,如何通过其中一篇文章的 ID 获取数据,这样如果我转到我的 angular 应用程序并单击 http://localhost:60300/perspectives/1/ I get the data of that one item. ( fyi, When i go to the index 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;
    });
 };

您需要使用 $routeParams:

What I've outline here will allow you to use the same controller here as that's what you've show in your config. Often-times, you'd assign a separate controller in your route (something like ArticleController, ArticleListController.). If you do that, the same process applies, but you wouldn't need to check if you have an ID parameter.

在您的控制器中:

  // 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)
    };

  })