sourcecode

구성 요소 Angular 2 내에서 리디렉션

copyscript 2023. 8. 27. 09:46
반응형

구성 요소 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>']);

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

}

이것은 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    
        }
    });
}

언급URL : https://stackoverflow.com/questions/32896407/redirect-within-component-angular-2

반응형