学習のangular9(ファイブ)

ナビゲーションルートのパラメータを送信

this.router.navigateByUrl('/user', { state: { orderId: 1234 } });
<a [routerLink]="/user" [state]="{ orderId: 1234 }">Go to user's detail</a>

状态将保留在浏览器的hostory.state属性上
在跳转到的页面上
export class DyTwoComponent implements OnInit {

  constructor(private router:Router) {
    console.log(this.router.getCurrentNavigation().extras.state);
  }

  ngOnInit(): void {
    console.log(history.state);
  }

}

注使用するピット、そのgetCurrentNaviagationあなたがする必要があるときconstructorに呼び出される、または電話、またはしないようにngOnInit、直接缶を取ります

レコードのスナップショット

我々/ccc/1のナビゲーション/ccc/123ニーズ現在のデータレコードを変更するには

export class DyTwoComponent implements OnInit {
  constructor(private r:ActivatedRoute) {
    r.url.subscribe((val)=>{
      console.log(val);
    })
  }
}    

ナビゲーションの変更ナビゲーション戦略

Vueがナビゲーションプログラミング内であると理解しました

相対ナビゲーション

  {
    path: 'two/:id',
    component: DyTwoComponent,
    children:[
      {
        path:'one',
        component:DyOneComponent
      },
      {
        path: 'ref',
        component: RefsComponent,
      }
    ]
  }

假设当前路由是 /two
<div (click)="clickDown('one')">跳one子路由</div>
<div (click)="clickDown('ref')">跳ref子路由</div>

export class DyTwoComponent implements OnInit {
  constructor(private router: Router, private r: ActivatedRoute) { }
  ngOnInit(): void {}

  clickDown(item: string) {
    this.router.navigate(['./' + item], {relativeTo: this.r})
      					'../' //那么会跳转到 /one  /ref 前面没有two
  }
}
跳转到 two/one
跳转到 two/ref
但是当 two/:id  是动态的跳转会报错,暂时不知道怎么解决

疑問符パラメータ

/results?page=1
this.router.navigate(['/results'], { queryParams: { page: 1 } });

ハッシュフラグメントURLのセット

/results#top
this.router.navigate(['/results'], { fragment: 'top' });

パラメータ合併

/results?page=1 to /view?page=1&page=2
this.router.navigate(['/view'], { queryParams: { page: 2 },  queryParamsHandling: "merge" });

次のフラグメントナビゲーションのための保持時間URL

/results#top   /view#top
this.router.navigate(['/view'], { preserveFragment: true });

歴史は記録されません。

this.router.navigate(['/view'], { skipLocationChange: true });

現在の履歴を交換してください

this.router.navigate(['/view'], { replaceUrl: true });

リフレッシュルーティング

/pro/1 切换到/pro/1221

 clickDown() {
    this.router.navigateByUrl('/pro/1221');
    this.router.routeReuseStrategy.shouldReuseRoute = function(){
      return false;
    };
  }
我们发现生命周期会重新执行

ルート

Configurationオブジェクトは、単一のルートを定義します

ワイルドカード

インスタンス化されたコンポーネントを実行するには、あなたがに移動どんなに、

[{
  path: '**',
  component: WildcardComponent
}]

リダイレクト

redirectTo

空路径

親パラメータとデータを継承空のパス

/チーム/ 12の例であり、AllUsersコンポーネント

[{
  path: 'team/:id',
  component: Team,
  children: [{
    path: '',
    component: AllUsers
  }, {
    path: 'user/:name',
    component: User
  }]
}]

マッチング戦略

前缀匹配
/team/12/user   /team/:id 匹配

{
  path: '',
  pathMatch: 'prefix', //default
  redirectTo: 'main'
}

  pathMatch: 'full', 完整匹配
  { path: '', redirectTo: 'list', pathMatch: 'full' },

ルーティングガード

トリガー順:

canload負荷

(重要)にcanActivate

サブルーティングを入力canActivateChild

canDeactivate休暇(重要)

私は簡単に以下を達成することができます

サービスを作成します

import {Injectable} from '@angular/core';
import {
  ActivatedRouteSnapshot,
  CanActivate,
  CanDeactivate,
  Router,
  RouterStateSnapshot
} from "@angular/router";
import {DyOneComponent} from "./dy-one/dy-one.component";

@Injectable({
  providedIn: 'root'
})
export class AuthGuardService implements CanActivate, CanDeactivate<DyOneComponent> {

  constructor(private router: Router) {
  }

  // 进入
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    const url: string = state.url;
    console.log(url);
    return true;
  }

  // 离开
  canDeactivate(component:DyOneComponent,currentRoute:ActivatedRouteSnapshot,currentState:RouterStateSnapshot) {

    return window.confirm('是否离开这个模块')
  }

}
DyOneComponent 是你离开这个页面所在的组件

ルーティング

  {
        path: 'home',
        component: HomeComponent,
        canActivate: [AuthGuardService],// 进入
        canDeactivate:[AuthGuardService] // 离开
   }

あなたは、ローリング位置ExtraOptions前に回復する必要があるかどうか

@NgModule({
  imports: [RouterModule.forRoot(routes,{ scrollPositionRestoration: 'enabled',})],
  exports: [RouterModule]
})

カスタムレコードをスクロール

  constructor(private router: Router, private viewportScroller: ViewportScroller) {
    this.router.events.pipe(
      filter((e: Scroll) => e instanceof Scroll)
    ).subscribe(
      e => {
        if (e.position) {
          // 后退
          viewportScroller.scrollToPosition(e.position);
        } else if (e.anchor) {
          // 哈希
          viewportScroller.scrollToAnchor(e.anchor);
        } else {
          // forward navigation
          viewportScroller.scrollToPosition([0, 0]);
        }
      }
    )
  }

決意

ジャンプの後に解決ルーティング性を保証データの取得を行う、空のコンポーネントデータ遅延を防止するためにケースが原因で発生

また、傍受のルートを解決するために使用することができます

常に問題が限りない方法は非常に厳密ではない文言がないので、そこにあると言います

路由
   {
        path: 'two/:id',
        component: TwoComponent,
        resolve: {
          detail: BlockService // 这个是拦截的路由
        }
      },
          
服务
import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot} from "@angular/router";
import {Observable} from "rxjs";
import {map} from "rxjs/operators";

@Injectable()
export class BlockService implements Resolve<any> {
  constructor(private router: Router) {
  }
  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
    let ids = route.paramMap.get('id');
    return new Observable(subscriber => {
      subscriber.next(11)
    }).pipe(
      map(res => {
        if (res == ids) { //成功
          return res
        } else {// 失败
          this.router.navigate(['/three']);
          return false
        }
      })
    ).subscribe(val => {
      return val
    })
  }

}
成功后才会展示那个组件

退会について考えることを忘れないでください、私はオンラインサブスクリプションをキャンセルする必要はありませんでした教えてください、また、特定のポイントを探る必要があります

おすすめ

転載: www.cnblogs.com/fangdongdemao/p/12640305.html