angular9 of Learning (Five)

Route navigation parameters passed

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

}

Note that a pit, when you use getCurrentNaviagationwhen you need to constructorbe called in, or not to call, or ngOnInitdirectly take can

Record Snapshot

We from /ccc/1the navigation /ccc/123needs to change the current data record

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

Navigation modify navigation strategy

Vue understood to be inside the navigation programming

Relative Navigation

  {
    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  是动态的跳转会报错,暂时不知道怎么解决

Question mark parameters

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

Set of hash fragment URL

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

Parameters merger

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

Retention time for the next fragment navigation URL

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

History does not record the

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

Replace the current history

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

Refresh routing

/pro/1 切换到/pro/1221

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

Route

Configuration object defines a single route

Wildcards

No matter where you navigate to, to perform the instantiated component

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

Redirect

redirectTo

Flying diameter

Empty path inherit the parent parameters and data

/ team / 12 are examples of AllUserscomponents

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

Matching strategy

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

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

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

Routing guard

Trigger order:

canload load

canActivate into the (important)

canActivateChild enter the sub-routing

canDeactivate leave (important)

I can only briefly achieve the following

Creating a service

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 是你离开这个页面所在的组件

routing

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

Whether you need to recover before rolling position ExtraOptions

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

Custom scroll through the records

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

resolve

performing resolve routing ensures data acquisition after the jump, preventing empty component occurs because of the case where data delay

It can also be used to resolve interception route

Always says there is a problem, as long as there is no way a not very strict wording

路由
   {
        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
    })
  }

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

Remember to think about unsubscribe, Tell me I did not have to cancel your subscription online, also need to explore the specific point

Guess you like

Origin www.cnblogs.com/fangdongdemao/p/12640305.html