簡體   English   中英

在組件 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' },
])

然后在您的組件導入中然后注入路由器

import {Router} from 'angular2/router'

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

你要做的最后一件事就是打電話

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

或者

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM