angular 如何在单页应用程序中将数据从一个页面传递到另一个页面

How to pass data from one page to another in single page application in angular

如何在 angular 单页应用程序中将数据或值从一个页面传递到另一个页面。这是我第一次将 angular/typescript 和 javascript 作为一个整体来工作。

我的objective是把userid传给edit user页面。 我正在使用

 "angular": "^1.7.2",
 "angular-route": "^1.7.2",

我现在的结构是这样的 在 route.js

app.config(function($routeProvider){
  $routeProvider
  .when('/',{
    templateUrl:'home.html'
  })
  .when('/user',{
    templateUrl:'showUsers.html'
  })
.when('/user-edit/:userId',{
  templateUrl:'editUser.html'
})
})

showUsers.html

<a href="#!user-edit/92">User Edit screen</a>

现在我想做的是在用户编辑屏幕的 jquery 脚本中捕获用户 ID,这样我就可以获得用户数据。

我该怎么做?

我正在关注

  1. https://www.w3schools.com/angular/angular_routing.asp
  2. https://docs.angularjs.org/tutorial

我也关注了一些关于堆栈溢出的问题

但这对我没有帮助。

使用 $routeParams 服务:$routeParams 服务允许我们检索路由参数。

var module = angular.module("myApp", ['ngRoute']);
module.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
        .when('/route1/:param1/:param2', {
            templateUrl: 'route1.html',
            controller: 'RoutingController'
        })
        .when('/route2/:param1/:param2', {
            templateUrl: 'route2.html',
            controller: 'RoutingController'
        })
        .otherwise({
            redirectTo: '/route1/default-book/default-page'
        });
}]);
module.controller("RoutingController", function ($scope, $routeParams, $location) {
    // Using $routeParams
    $scope.param1 = $routeParams.param1;
    $scope.param2 = $routeParams.param2;
});

在您的路由器配置中,您的配置类似于 /user-edit/:userId

然后点击锚标记,您的 url 将是(例如),

http://some-sitename.com#/user-edit/92

所以使用$routeParams

在您的编辑控制器中 $routeParams.userId 将为您获取所需的值,即在您的情况下为 92。

深度你可以像这样使用它,

app.controller("EditController", function ($scope, $routeParams) {
    // Using $routeParams
    $scope.userId = $routeParams.userId;

     $scope.editMethod = function() {
         // inside this method use $scope.userId
      };

});