标签: angular-routing

在使用routeProvider在Angular中启动路由之前,如何检查登录或其他状态?

假设我有4条路线--2要求用户登录,2则不需要.我的app init看起来像:

        $routeProvider.when('/open1',{templateUrl:'/open1.html',controller:'Open1'});
        $routeProvider.when('/open2',{templateUrl:'/open2.html',controller:'Open2'});
        $routeProvider.when('/secure1',{templateUrl:'/secure1.html',controller:'Secure1'});
        $routeProvider.when('/secure2',{templateUrl:'/secure2.html',controller:'Secure2'});
Run Code Online (Sandbox Code Playgroud)

路由/open1/open2向所有人开放,而路线/secure1/secure2需要进行登录的用户,如果没有,采取一些行动,例如重定向到登录或启动一个警告.我可以通过使用我的Auth服务和呼叫来确定用户的状态,例如Auth.isLogin().结果将是:

  • 转到/open1/open2始终转到上面声明的模板和控制器
  • 如果Auth.isLogin()返回true,/secure1并且/secure2到上面去申报模板和控制器
  • if Auth.isLogin()返回false,/secure1/secure2采取其他一些操作,例如$location.path('/login')

可以把逻辑放在Secure1Secure2检查的控制器中,但这是重复的,混淆了责任,使它们更难测试等.

有没有办法可以$routeProvider用来声明,"检查这条路线和这条路线,如果没有,重定向"?我想用resolve某种方式,但不太确定如何使用它(文档resolve不是很清楚,几个有用的例子).

编辑:

根据以下答案,看来有三种理念可以做到这一点:

第二个选项是两位回答者提出的建议.

angularjs angular-routing

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

Angular中的未知$ http提供程序

我需要$http在config方法中使用service.但我无法$http在配置中使用,我收到unknown Provider错误消息.

我的代码:

.config(function($http, $routeProvider, $provide) {
    $http.get("sampleslist.js").success(function(data) {
        var loop = 0, currentRoute;

        for (loop = 0; loop < data[loop].pages.length; loop++) {
            currentRoute = data[loop].pages;

            var routeName = "/" + currentRoute[loop].name;
            $routeProvider.when(routeName, {
                templateUrl:"/" + currentRoute.name + ".html",
            })
        }
    })

    app = {controller: $controllerProvider.register}
})
Run Code Online (Sandbox Code Playgroud)

你能为此提供解决方案吗?

javascript angularjs angular-routing angularjs-directive

9
推荐指数
1
解决办法
312
查看次数

如何在Angular 2中将路径数据导入App组件

我在我的应用程序路由模块中定义了一些路由数据,如下所示:

    const appRoutes:Routes = [
  {path: '', component: LoginComponent, data:[{PageName:"Login Page"}]}]
Run Code Online (Sandbox Code Playgroud)

我想全局获取数据,所以我使用app.component.ts来获取URL重定向相关信息,如下所示:

export class AppComponent {
  title = 'Welcome';
  constructor(public router: Router, public authenticationService: AuthenticationService) {
    this.router.events.subscribe(event => {
        console.log("Url",event.urlAfterRedirects);
        console.log("Page Name", router[PageName]); //Not working
      }
Run Code Online (Sandbox Code Playgroud)

我尝试注入ActivatedRoute,但每次重定向后都没有更新.

无论如何,我可以在哪里配置页面名称并在全球范围内获取它app.component.ts.

javascript angular-routing angular

9
推荐指数
3
解决办法
2万
查看次数

角度路由:是否可以为不同的语言使用不同的"路径"字符串?

我正在做一个i18n Angular应用程序,到目前为止效果很好.

但是我有不同语言的相同路由字符串,这不是最好的SEO.

对于每种语言,路径数组的"路径"属性是否可能不同?

例如:

const appRoutesEN: Routes = [
  { path: 'crisis-center', component: CrisisListComponent },
  { path: 'hero/:id',      component: HeroDetailComponent },
  {
    path: 'heroes',
    component: HeroListComponent,
    data: { title: 'Heroes List' }
  },
  { path: '**', component: PageNotFoundComponent }
];
Run Code Online (Sandbox Code Playgroud)

是否可以定义appRoutesFR: Routes如果我可以使用它?我要注入LOCALE_ID路由模块吗?如果是这样的话?

angular-routing angular

9
推荐指数
1
解决办法
2970
查看次数

在router.navigate之后没有调用ngOnInit

我的Angular应用程序突然没有调用ngOnInit(),router.navigation()这意味着我的组件无法正确加载.我认为这可能是由于我做出的一些改变,但恢复改变并没有解决问题.

正常导航导致组件无法正确加载的示例; 此页面由以下代码列表导航 this.router.navigate(['/result', this.params.data._id]);:

组件未正确加载

重新加载页面,组件正确加载:

组件正确加载

以下是我的一些代码清单,

app.module.ts

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule,
    AgGridModule.withComponents(
            [SampleResultButtonComponent]
        ),
    ChartsModule
  ],
  declarations: [
    AppComponent,

    LoginComponent,
    LogoutComponent,
    SignupComponent,

    FilesComponent,
    NavbarComponent,
    ProfileComponent,
    UploadComponent,
    SampleGridApplicationComponent,
    SampleResultButtonComponent,
    AssetGridApplicationComponent,
    ResultComponent,
    ResetPasswordComponent,
    AssetComponentDetailComponent
  ],
  bootstrap: [ AppComponent ],
  entryComponents: [AssetComponentDetailComponent]
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

APP-routing.module.ts

    @Injectable()
export class NoAuthGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate() {
    const activeUser = Kinvey.User.getActiveUser();
    if (activeUser) {
      return true;
    }

    // Navigate to the …
Run Code Online (Sandbox Code Playgroud)

angular-routing angular-cli angular

9
推荐指数
2
解决办法
2923
查看次数

如何使用带有路由器插座的 sidenav 和带有路由器插座的单独登录?

我正在尝试实现一个带有登录页面的应用程序,然后当用户登录时,会有一个导航栏、工具栏和 sidenav 带有router-outlet.

基本上,在app.component.html我有一个定义:

<div *ngIf="isAuthenticated">
    <app-custom-navbar></app-custom-navbar>
    <app-custom-toolbar></app-custom-toolbar>
    <app-custom-sidenav></app-custom-sidenav>
</div>

<router-outlet></router-outlet>
Run Code Online (Sandbox Code Playgroud)

我有这个路由:

const routes: Routes = [
    { path: '', canActivate: [AuthenticationGuard], component: HomeComponent },
    { path: 'login', component: LoginComponent },
    { path: 'data', canActivate: [AuthenticationGuard], component: DataComponent },
    { path: 'projects', canActivate: [AuthenticationGuard], component: ProjectsComponent },
];
Run Code Online (Sandbox Code Playgroud)

因此,这很有效,如果用户未通过身份验证,他将被重定向到/login.

问题是,当他通过身份验证时,sidenav 组件占据了整个空间,然后其他组件就看不到了。

基本上这是问题:

<mat-sidenav-container class="sidenav-container">
  <mat-sidenav>

    <!-- sidenav template... -->

  </mat-sidenav>
  <mat-sidenav-content>

   <!-- how can I put my content here and use routing at the …
Run Code Online (Sandbox Code Playgroud)

angular-routing angular-material angular-material2 angular angular-router

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

Angular 5 - 动态基准引用导致重复加载bundle | chunk

我在项目中使用Angular 5.2版本.我在index.html中动态设置基本引用,以满足不同客户端的不同URL.

应用主页面网址如下所示: -

http://example.com/client1/app/login
http://example.com/client2/app/login
http://example.com/client3/app/login
Run Code Online (Sandbox Code Playgroud)

client1,client2等是IIS 中的虚拟目录.

当我在浏览器中运行应用程序时,我可以从检查窗口看到重复的块正在加载并导致应用程序页面变慢.

有一件事我观察了重复块的Web请求URL.让我们说script.xxxxxxxxxxxxxxxxxxxxxx.bundles.css.

第一个网络请求: - https://example.com/client1/scripts.7186135389ca4b63fab4.bundle.js

第二个网络请求(重复): - https://example.com/scripts.7186135389ca4b63fab4.bundle.js

不需要第二个Web请求.我无法估计它是如何出现的.

在此输入图像描述

Index.html在我的项目中看起来像这样: -

<!doctype html>
<html lang="en">

    <head>
        <meta charset="utf-8">
        <title>Web</title>
        <link href="/assets/Images/favicon.ico" rel="shortcut icon" type="image/x-icon">
        <base id="baseHref" href="/">
        <script>
            (function () {
                if (window.location.hostname !== 'localhost') document.getElementById('baseHref').href = "/" + window.location.pathname.split('/')[1] + "/";
            })();
        </script>
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
      <app-root></app-root>
    </body>
    </html>
Run Code Online (Sandbox Code Playgroud)

请建议,如何纠正这个问题.

angular-routing angular angular5

9
推荐指数
1
解决办法
815
查看次数

Angular 中 onSameUrlNavigation 属性的用途是什么(版本大于 5)

最近我听说了一个名为onSameUrlNavigation的属性,您可以在其中将其设置为“重新加载”。我在谷歌上搜索过它,但没有多少文章展示了该属性的使用。有人可以帮助我提供一个实时示例,说明我们究竟需要在哪里使用该属性。

@ngModule({
 imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’})],
 exports: [RouterModule],
 })
Run Code Online (Sandbox Code Playgroud)

angular-routing angular

9
推荐指数
4
解决办法
2万
查看次数

使用赛普拉斯测试 Angular 时如何防止整页重新加载?

当我为 Angular 应用程序编写 Cypress e2e 测试时,我经常使用这样的visit()命令:

.visit('/foo/bar')

这样就完成了工作,即 Cypress 导航到/foo/bar,但整个应用程序会重新加载。这非常慢,并且不会模仿实际的用户行为。

是否可以在不重新加载整页的情况下导航/访问 Angular 应用程序?

我确实尝试过:

cy.window().then((win) => {
   win.history.pushState({}, '', '/foo/bar')
})
Run Code Online (Sandbox Code Playgroud)

但是 angular 对此没有反应。

angular-routing angular cypress

9
推荐指数
2
解决办法
2989
查看次数

ngmodule 不是子类型 ngmoduletype

我使用 angular 9 并且我想做延迟加载 app-routing

{
    path: '', loadChildren: () => import("./components/login/login.module")//.then(m =>
     // m.LoginModule)
  }
Run Code Online (Sandbox Code Playgroud)

在我创建登录模块之后:

@NgModule({
    declarations: [LoginComponent],
    imports: [
        CommonModule,
        FormsModule,
        LoginModuleRouting

    ],
    providers:[]
})
export class LoginModule { }
Run Code Online (Sandbox Code Playgroud)

和路由:

const routes: Routes = [
  {
    path: '', component: LoginComponent,

  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})


export class LoginModuleRouting { }
Run Code Online (Sandbox Code Playgroud)

问题是,当我打电话ng serve并继续访问 ` http://localhost:4200/ 时,我得到了这个异常:

core.js:6237

 ERROR Error: Uncaught (in promise): Error: ASSERTION ERROR: NgModule '[object Module]' is not a …
Run Code Online (Sandbox Code Playgroud)

angular-routing angular-module angular angular9

9
推荐指数
3
解决办法
7071
查看次数