组件Angular 2中的重定向

Thr*_*nts 69 javascript angular

我有一个简单的方法,在它的最后我想重定向到另一个组件:

export class AddDisplay{
  display: any;

  addPairTo(name: string, pairTo: string){
    this.display = {};
    this.display.name = name;
    this.display.pairTo = pairTo;

  }
}
Run Code Online (Sandbox Code Playgroud)

我想做的是在方法结束时重定向到另一个组件:

export class AddDisplay{
  display: any;

  addPairTo(name: string, pairTo: string){
    this.display = {};
    this.display.name = name;
    this.display.pairTo = pairTo;

    this.redirectTo('foo');
  }
}
Run Code Online (Sandbox Code Playgroud)

我如何在Angular 2中实现这一目标?

kit*_*kit 87

首先配置路由

import {RouteConfig, Router, ROUTER_DIRECTIVES} from 'angular2/router';
Run Code Online (Sandbox Code Playgroud)

@RouteConfig([
  { path: '/addDisplay', component: AddDisplay, as: 'addDisplay' },
  { path: '/<secondComponent>', component: '<secondComponentName>', as: 'secondComponentAs' },
])
Run Code Online (Sandbox Code Playgroud)

然后在组件导入中然后注入Router

import {Router} from 'angular2/router'

export class AddDisplay {
  constructor(private router: Router)
}
Run Code Online (Sandbox Code Playgroud)

你要做的最后一件事就是打电话

this.router.navigateByUrl('<pathDefinedInRouteConfig>');
Run Code Online (Sandbox Code Playgroud)

要么

this.router.navigate(['<aliasInRouteConfig>']);
Run Code Online (Sandbox Code Playgroud)

  • 注意:此答案涉及Angular 2的beta版或候选版本,不再适用于Angular 2 final. (9认同)

小智 7

这对我有用 Angular cli 6.x:

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

constructor(private artistService: ArtistService, private router: Router) { }

  selectRow(id: number): void{
       this.router.navigate([`./artist-detail/${id}`]);

  }
Run Code Online (Sandbox Code Playgroud)


小智 5

@ kit的答案没问题,但请记住添加ROUTER_PROVIDERS到组件中的提供程序.然后您可以重定向到ngOnInit方法中的另一个页面:

import {Component, OnInit} from 'angular2/core';
import {Router, ROUTER_PROVIDERS} from 'angular2/router'

@Component({
    selector: 'loginForm',
    templateUrl: 'login.html',
    providers: [ROUTER_PROVIDERS]
})

export class LoginComponent implements OnInit {

    constructor(private router: Router) { }

    ngOnInit() {
        this.router.navigate(['./SomewhereElse']);
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 注意:此答案涉及Angular 2的beta版或候选版本,不再适用于Angular 2 final. (23认同)
  • @jbandi,您能再提供一个更新的答案吗? (2认同)