组件内重定向 Angular 2

82

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

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中实现这个?


我只能想到路由。你可以使用navigate来实现。 - Eric Martinez
4个回答

103

首先配置路由

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

FYI:navigateByUrl 不接受数组,只能接受单个字符串。 - Ben Thielker
1
如何重新加载视图?navigatenavigateByUrl似乎会更改URL,但绑定到该路由的组件不会重新加载。 - dopatraman
9
注:本回答针对 Angular 2 的 beta 或候选版本,已不适用于 Angular 2 正式版。 - jbandi

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

}

23
注意:本答案讨论的是 Angular 2 的 beta 或 release-candidate 版本,对于 Angular 2 正式版已不再适用。 - jbandi
2
@jbandi,您能否提供一个更新的答案呢? - Hugo

8

以下内容适用于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}`]);

  }

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

嗨,PYRO BUG,欢迎。请考虑添加一些解释。 - Tiago Martins Peres

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接