以编程方式在 Angular 4.2.2 中重定向

Bla*_*ite 2 angular

我正在构建一个玩具应用程序,它有一个默认的搜索页面,然后它有一个管理页面。单击“搜索”页面上的按钮可调用管理页面。我的这个过程的代码是这样的:

  constructor( private searchResultService: SearchService, private router: Router) {
    ....
  }

  goToAdminLogin(ev): void
  {
    this.router.navigate(['adminLogin'])
  }
Run Code Online (Sandbox Code Playgroud)

但是,单击 Button 时唯一会改变的是地址栏。

在我的 app.module.ts 中,我有这个:

RouterModule.forRoot([
  {
    path: 'search',
    redirectTo: '/search',
    pathMatch: 'full'
  },
  {
    path: 'adminLogin',
    component: AdminLoginComponent
  }
])
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我检查了我的控制台,我没有看到它发出任何错误消息。有谁知道为什么我的重定向无处可去?

任何帮助是极大的赞赏。

编辑:添加 AdminLoginComponent:

我的 AdminLoginComponent 如下所示:

import {Component, Inject, Input} from '@angular/core';
import {SearchService} from '../services/search.service';
import {SearchResponse} from '../remote/search-response';

@Component({
  selector: 'admin-login-component',
  templateUrl: './admin-login.component.html',
  styleUrls: ['./admin-login.component.css']
})
export class AdminLoginComponent {

  constructor( private searchResultService: SearchService)  {
  }
}
Run Code Online (Sandbox Code Playgroud)

我的“admin-login.component.html”非常简单,如下所示:

<div>Hello</div>
Run Code Online (Sandbox Code Playgroud)

编辑:解决方案

多亏了 Debbie K,解决方案基本上是从我的 app.component.* 中删除我的第一个 UI,并将它放在一个子组件中,类似于我的管理员登录设置。我的 app.component.html 现在看起来像这样:

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

Deb*_*ahK 8

尝试这个:

this.router.navigate(['/adminLogin'])
Run Code Online (Sandbox Code Playgroud)

并设置路由器插座的层次结构:

应用程序组件.html

<router-outlet> <-- 这将显示整页的任何内容。

主页.component.html

<header of menu stuff here>

<router-outlet> <-- 这将显示页眉/页脚中的任何内容

<footer stuff here>

我这里的速记有意义吗?


Har*_*Das 6

这包括三个简单的步骤:

  1. 导入路由器

    import {Router} from '@angular/router';

  2. 在构造函数中

    constructor(private router: Router){}

  3. 导航到不同的路由器

    this.router.navigate(['/about']);

导航到一个 URL

`this.router.navigateByUrl('/home');`
Run Code Online (Sandbox Code Playgroud)