Angular:ルートへの手動リダイレクト


89

最近、angular.js1の代わりにangular4を使い始めました。

私はヒーローのチュートリアルに従ってAngular4の基礎について学びました。現在、「@ angular / router」パッケージのAngular独自の「RouterModule」を使用しています。

アプリケーションに認証を実装するために、別のルートに手動でリダイレクトする方法を知りたいのですが、インターネット上でこれに関する有用な情報を見つけることができないようです。

回答:


225

角度ルーティング:手動ナビゲーション

まず、Angularルーターをインポートする必要があります。

import {Router} from "@angular/router"

次に、それをコンポーネントコンストラクターに挿入します。

constructor(private router: Router) { }

そして最後に、.navigate「リダイレクト」する必要がある場所でメソッドを呼び出します。

this.router.navigate(['/your-path'])

次のようなパラメータをルートに配置することもできますuser/5

this.router.navigate(['/user', 5])

ドキュメント:Angularの公式ドキュメント


8

例:app.home.htmlのイベントのangularjs4ボタンでのリダイレクト

<input type="button" value="clear" (click)="onSubmit()"/>

とhome.componant.tsで

 import {Component} from '@angular/core';
 import {Router} from '@angular/router';

 @Component({
   selector: 'app-root',
   templateUrl: './app.home.html',
 })

 export class HomeComponant {
   title = 'Home';
   constructor(
     private router: Router,
    ) {}

  onSubmit() {
    this.router.navigate(['/doctor'])
 }
 }


3

Angular Redirectionを手動で:インポート@angular/router、インジェクトしてconstructor()から呼び出しますthis.router.navigate()

import {Router} from '@angular/router';
... 
...

constructor(private router: Router) {
  ...
}

onSubmit() {
  ...
  this.router.navigate(['/profile']); 
}

1

これを試して:

constructor(  public router: Router,) {
  this.route.params.subscribe(params => this._onRouteGetParams(params));
}
this.router.navigate(['otherRoute']);

1

component.tsファイルの関数を使用して別のページにリダイレクトします##

   componene.ts-
   ------------------------------------------------------------------------  
   import {Router} from '@angular/router';

   constructor(private router: Router) {}

   OnClickFunction()
   {
        this.router.navigate(['/home']);
   }

  component.html-
  ----------------------------------------------------------------------------------- 

     <div class="col-3">                  
         <button (click)="OnClickFunction()" class="btn btn-secondary btn-custom mr- 
          3">Button Name</button>
    </div>   

1

あなたはあなたの質問に対して十分な正解を持っているかもしれませんが、あなたのIDEがあなたに警告を与える場合に備えて

ナビゲートから返された約束は無視されます

その警告を無視するか、を使用することができますthis.router.navigate(['/your-path']).then()


0

これはうまくいくはずです

import { Router } from "@angular/router"

export class YourClass{

   constructor(private router: Router) { }

   YourFunction() {
      this.router.navigate(['/path']);
   }

}
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.