组件Angular 2中的重定向

时间:2015-10-01 20:35:32

标签: javascript angular

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

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中实现这一目标?

4 个答案:

答案 0 :(得分:79)

首先配置路由

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>']);

答案 1 :(得分: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']);
    }

}

答案 2 :(得分:3)

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

  }

答案 3 :(得分:1)

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    
        }
    });
}