标签: angular-routing

Angular.js - 通过$ route或$ routeParams访问params

我有一个控制器,我在其中注入$ route和$ routeParams但是当我去获取值时

$ route.routes.current.params.test - >> current is undefined $ routeParams.test - >> test is undefined

当我使用console.log($ route)或console.log($ routeParams)时,两个对象似乎都正确填充

我很困惑.如何为console.log提供值,但在我执行console.log的同一个控制器中失败?

更新:示例代码

    angular.module('TestApp')
        .controller('TestController', ['$scope', '$http', '$routeParams', '$route',
            function($scope, $http, $routeParams, $route) {
                console.log($routeParams);
                //console.log($routeParams.test);
                console.log($route.current.test);
                //console.log($route.routes);

            }]);
Run Code Online (Sandbox Code Playgroud)

angularjs angular-routing

7
推荐指数
1
解决办法
1万
查看次数

从模板(视图)中动态加载AngularJS模块

背景: 我们假设为了论证你有100,000个视图(部分).我们还假设您具有视图范围的控制器,以及可能的视图范围的服务和过滤器.尝试设想一个托管100,000个不同的小应用程序的聚合应用程序.

问题: 当你有需要附带控制器的"部分"时,典型的解决方案是做这样的事情:

$routeProvider.when('/app1', {
        templateUrl: 'partials/view1.html',
        controller: 'controller1'
    });
Run Code Online (Sandbox Code Playgroud)

控制器通常从index.html通过以下方式加载:

<script src="js/directives/Controller1.js"></script>
Run Code Online (Sandbox Code Playgroud)

这种方法的问题在于它不能扩展.有动态加载控制器的解决方案,但它们仍然需要在各种配置中添加触摸点.

理想的解决方案: 理想情况下 - 对于数量在000的非常小的应用程序,控制器可以动态加载,也可以从部分内部加载.这将减轻管理多个文件和几个配置触摸点(更不用说网络请求)的需要,并且保持每个部分非常好.

它看起来像这样:

在路由器中:

$routeProvider.when('/apps/:appId', {
        templateUrl: 'partials/app-frame.html',
        controller: 'AppCtrl'
    });
Run Code Online (Sandbox Code Playgroud)

在包含html(app-frame)中包含相对不同的"迷你app":

<h1>Currently hosting {{appId}}</h1><hr>
<div class="ng-include: appUrl"></div>
Run Code Online (Sandbox Code Playgroud)

在使用appUrl进行部分解析时,在一个中定义控制器标记:

<script>
  myApp.controller('controller1', ['$scope', function ($scope) {
    $scope.foo = "bar";
  }]);
</script>


<div ng-controller="controller1">
     {{foo}}
</div>
Run Code Online (Sandbox Code Playgroud)

对于这样的情况,有很多部分和控制器和视图的1-1映射,将两者结合起来以提高开发效率和维护是有意义的.它比使用多个文件和其他配置触摸点更清晰.

问题是,这不起作用.它可能就像在应用指令之前强制加载脚本一样简单......但不知道如何做到这一点?

以下是对该问题的一些类似解释:

https://groups.google.com/forum/#!topic/angular/H4haaMePJU0

使用Angular和Compile加载部分页面控制器

来自AngularJS团队的Igor说:

I see.. we looked into supporting script tags in jqlite, but what needs to be done to get a cross-browser support …
Run Code Online (Sandbox Code Playgroud)

angularjs angular-routing angular-template

7
推荐指数
1
解决办法
3920
查看次数

使用node.js时,Angular Ui-Router不进行路由

我正在使用角度ui路由器.路由器似乎在主页index.html上运行完美.但任何其他导航都不起作用.

这是我的stateprovider angular:

var app = angular.module('myApp', ['ui.router']);


app.config(function($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise("/");

    $stateProvider
        .state("home", {
            url: "/",
            templateUrl: "../partials/home/index.html"
        })
        .state("login", {
            url:"/login",
            templateUrl: "../partials/account/login.html"
        })
        .state("register", {
            url: "/register",
            templateUrl: "../partials/account/register.html"
        })
        .state("values", {
            url: "/values",
            templateUrl: "../partials/test/values.html"
        })
    ;
});
Run Code Online (Sandbox Code Playgroud)

主要index.html中的HTML:

 <!--Content -->
    <div class="container">
        <div ui-view></div>
    </div>
    <!-- END Content -->
Run Code Online (Sandbox Code Playgroud)

当我浏览localhost:8080/login页面时,我得到了这个:

在此输入图像描述 如果它找不到,我想我甚至不应该看到这个页面.由于$ urlRouterProvider.otherwise(),它不应该将我重定向回"/".除此之外,模板url /partials/account/login.html存在.

我对node.js有些新意,我很好奇,如果笔记文件服务器试图路由并打败我的角度文件服务器?我使用的是http-server,这可能是最常见的.

如果有帮助,我也在使用Express Node.以下是app.js的代码,我认为问题可能来自:

var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = …
Run Code Online (Sandbox Code Playgroud)

node.js angularjs angular-routing

7
推荐指数
1
解决办法
7393
查看次数

使用带路由的ngUpgrade引导Angular 2 rc.6混合应用程序

我有一个Angular 1/Angular 2混合应用程序正在使用rc.3和不推荐的路由器.从我能找到的所有资源中,rc.5是迈向新路由器的重要一步.我可以启动我的混合应用程序,并渲染我的根组件,但路由不起作用.

var upgradeAdapter = new UpgradeAdapter(forwardRef(() => AppModule));

angular.module('ng1App', [])
  .directive('myBaseComponent', <any>upgradeAdapter.downgradeNg2Component(MyBaseComponent));

@NgModule({
  imports: [BrowserModule, routing],
  providers: [appRoutingProviders, HTTP_PROVIDERS],
  declarations: [MyBaseComponent,
    MyNG2RoutableComponent]
})
class AppModule { }


upgradeAdapter.bootstrap(document.body, ['ng1App']).ready(function(){
  console.log('bootstraped!');
});
Run Code Online (Sandbox Code Playgroud)

我的根NG2组件引导,因为我可以在它呈现的模板中抛出东西.但是,当我添加它时,它似乎<router-outlet></router-outlet>不会渲染子路径.如果我在没有upgradeAdapter的情况下仅启动我的NG2应用程序,一切都按预期工作.

我觉得我只缺少一个连接件.有任何想法吗?


Angular RC.6和路由器RC.2更新

我上周升级到rc.6和rc.2版本的路由器,同样的问题.当不涉及路由时,UpgradAdapter非常有用.一旦我拉入路由器插座,然后没有任何渲染,没有错误.

javascript angular-routing ng-upgrade angular

7
推荐指数
1
解决办法
541
查看次数

Angular 4路由器:阻止直接浏览器导航

如何说服Angular 4路由器在我的应用程序中禁用直接浏览器导航?

我已经查看了路由器钩子CanActivateCanDeactivate实现了它们,但CanDeactivate在使用直接浏览器导航时根本不会触发.

我可以CanActivate用来阻止网址,但只有在应用程序重新启动后,这需要时间和浏览器窗口中的不需要的更改.

我希望能够在应用重新启动之前捕获直接浏览器导航.

如果这有帮助:我想完全禁止直接浏览器导航,所以我不需要允许某些网址并禁用其他网址的解决方案.

这是我的路由器定义:

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: 'dashboard', component: DashboardComponent, canActivate: [RouteGuardService] },
  { path: 'users', component: UsersMainComponent, canActivate: [RouteGuardService] },
  { path: 'vendors', component: VendorMainComponent, canActivate: [RouteGuardService] },
  { path: 'invoices', component: InvoicesMainComponent, canActivate: [RouteGuardService] },
  { path: 'offers' , component: EsdMainComponent, canActivate: [RouteGuardService] },
  { path: 'settings' , component: SettingsMainComponent, canActivate: [RouteGuardService] },
  // Callback …
Run Code Online (Sandbox Code Playgroud)

angular-routing angular angular4-router

7
推荐指数
2
解决办法
6795
查看次数

如果未保存更改,Angular 2/4会阻止用户离开组件

我有这个界面,我用来阻止用户离开页面

export interface ComponentCanDeactivate {
  canDeactivate: () => boolean;
}

@Injectable()
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
  canDeactivate(component: ComponentCanDeactivate): boolean {
    return  component.canDeactivate() ?
     //code : //more code
  }
}
Run Code Online (Sandbox Code Playgroud)

在我的一个组件中,我有以下代码

export class DashboardComponent implements ComponentCanDeactivate{
  @HostListener('window:beforeunload')
  canDeactivate(): boolean {
    return !this.isDirty;
  }
Run Code Online (Sandbox Code Playgroud)

我的问题是来自PendingChangesGuard的我的组件 - >(component:ComponentCanDeactivate)总是为空,所以我得到一个错误说

无法调用null的canDeactivate()

我的路由也有这个设置

 path: 'dashboard',
        canDeactivate: [PendingChangesGuard],
        loadChildren: './views/dashboard/dashboard.module#DashboardModule'
Run Code Online (Sandbox Code Playgroud)

谁能告诉我我做错了什么?

angular-routing angular angular-router-guards

7
推荐指数
1
解决办法
3450
查看次数

如何在 Angular 2(路由器 3)中处理租户子域

尝试在 Angular 2(RC6,路由器 3.0)中设置tenant.app.com

是否有关于如何执行此操作的文档?我看到的几乎所有内容都以 base url = / 开头,然后从 base url 解析 url。

我需要为非登录用户提供 www 版本,然后为所有登录用户提供租户驱动的子域

multi-tenant angular-routing angular

6
推荐指数
1
解决办法
6070
查看次数

Angular JS:URL 参数出现在 `#!/` 之前并且没有出现在 $location.search() 中

我正在将其他人制作的一个现有的小型 Angular JS 应用程序集成到一个不是用 Angular 构建的现有网站中。

所有 Angular JS 应用程序文件都保存在一个完全独立的目录中,然后用户可以单击链接将它们带到该子目录的索引。例如:

<a href="/path/to/angular-app/?returnUrl=/original/location">Login.</a>
Run Code Online (Sandbox Code Playgroud)

正如您在上面看到的,我需要传递一个名为returnUrl. 然后我需要在 Angular JS 应用程序中获取这个值,使用:

<a href="/path/to/angular-app/?returnUrl=/original/location">Login.</a>
Run Code Online (Sandbox Code Playgroud)

然而,这实际上返回一个空对象。我认为这是因为 Angular JS在 URL 参数之后附加#!/login在URL 上,如下所示:

example.com/path/to/app?returnUrl=/original/location/#!/login
Run Code Online (Sandbox Code Playgroud)

如果我在浏览器中修改 URL,将returnUrl参数移动到 URL 的末尾并刷新页面,它会工作并$location.search()返回{returnUrl: "/original/location/"}. 但是,据我所知,我无法在我的网站上更改此参数,因为该参数是指向 Angular JS 应用程序的链接的一部分,#!/login随后会自动添加。

我是新的 AngularJS,所以请尽可能清楚地解释:

  1. 这里发生了什么?为什么是URL参数之前#!/login
  2. 为什么这会阻止$location.search()返回任何东西?如果我将参数移动到结果 URL 的末尾,它就可以工作。
  3. 我能做些什么来解决这个问题?

javascript angularjs angular-routing

6
推荐指数
1
解决办法
1842
查看次数

角度路由 - 路径顺序重要吗?

app.module.ts 文件中列出的路径顺序重要吗?例如...

   RouterModule.forRoot([
      {path:'',component:HomeComponent},
      {path:'followers',component:GithubFollowersComponent},
      {path:'followers/:username/:userid',component:GithubProfileComponent},
      {path:'posts',component:PostsComponent},
      {path:'**',component:NotFoundComponent}
    ])
Run Code Online (Sandbox Code Playgroud)

对比..

  RouterModule.forRoot([
      {path:'',component:HomeComponent},
      {path:'followers/:username/:userid',component:GithubProfileComponent},
      {path:'followers',component:GithubFollowersComponent},
      {path:'posts',component:PostsComponent},
      {path:'**',component:NotFoundComponent}
    ])
Run Code Online (Sandbox Code Playgroud)

我正在看一个教程,它说顺序很重要..但我尝试了两种方法,它们似乎都按预期工作......

如果我将通配符路径( ** )移到顶部,那么是的,我确实注意到了差异。但是对于其他人来说,顺序根本不重要吗?还是我在这里遗漏了什么?....

angular-routing angular

6
推荐指数
1
解决办法
1987
查看次数

在 Angular Interceptors 中获取当前路线

我想知道是否有办法在 Angular 的 HttpInterceptor 中检索当前路由。我正在使用来自不同路线的相同拦截器,但我需要检查是否正在从特定路线使用拦截器。如果是这样,我想在执行之前向后端请求添加一个特定的标头。

似乎RouteRouterActivatedRouteActivatedRouteSnapshot对此不起作用。

我目前使用windows.location作为临时解决方案,但想知道在 HttpRequest 拦截器中执行此操作的正确方法是什么。

我目前的代码:

@Injectable()
export class APIClientInterceptor implements HttpInterceptor {
  constructor() {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    // Check if the call is done from the embed route.
    if (currentLocation.includes('/embed/')) {

      // Get the hash ID.
      const sIndex = currentLocation.lastIndexOf('/') + 1;
      const sLength = currentLocation.length - sIndex;
      const embedHash = currentLocation.substr(sIndex, sLength);
      console.log(embedHash);

      // Add the header to tell the …
Run Code Online (Sandbox Code Playgroud)

interceptor angular-routing angular-http-interceptors angular angular-router

6
推荐指数
1
解决办法
1963
查看次数