在组件内重定向 Angular 2

Redirect within component Angular 2

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

export class AddDisplay{
  display: any;

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

  }
}

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

export class AddDisplay{
  display: any;

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

    this.redirectTo('foo');
  }
}

如何在 Angular 2 中实现此目的?

先配置路由

import {RouteConfig, Router, ROUTER_DIRECTIVES} from 'angular2/router';

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

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

import {Router} from 'angular2/router'

export class AddDisplay {
  constructor(private router: Router)
}

您要做的最后一件事就是致电

this.router.navigateByUrl('<pathDefinedInRouteConfig>');

this.router.navigate(['<aliasInRouteConfig>']);

@kit的回答还可以,但是记得在组件中的providers加上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']);
    }

}

这对我有用 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}`]);

  }
callLog(){
    this.http.get('http://localhost:3000/getstudent/'+this.login.email+'/'+this.login.password)
    .subscribe(data => {
        this.getstud=data as string[];
        if(this.getstud.length!==0) {
            console.log(data)
            this.route.navigate(['home']);// used for routing after importing Router    
        }
    });
}