路由定位:
modifyUser(user) { this.router.navigate(['/auction/users', user.id]); }
路由定义:
{path: 'users/:id', component: UserModifyComponent, resolve: {user: UserResolve}},
UserResolve:
import {Injectable} from '@angular/core'; import {ActivatedRouteSnapshot, Resolve, RouterStateSnapshot} from '@angular/router'; import {User} from '../entity/user'; import {Observable} from 'rxjs/Observable'; import {UserService} from './user.service'; @Injectable() export class UserResolve implements Resolve<User> { constructor(private userService: UserService) { } resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<User> | Promise<User> | User { return this.userService.getUserById(route.params.id); } }
获取数据:
this.activatedRoute.data.subscribe((data) => this.model = data.user);
userService:
import {Injectable} from '@angular/core'; import {HttpClient, HttpParams} from '@angular/common/http'; import {Observable} from 'rxjs/Observable'; @Injectable() export class UserService { constructor(private http: HttpClient) { } queryUsers(userName, fullName): Observable<any> { const params = new HttpParams() .set('userName', userName) .set('fullName', fullName); return this.http.get('/api/users', {params}); } getUserById(id): Observable<any> { const url = '/api/users/' + id; return this.http.get(url); } deleteUser(id): Observable<any> { const url = '/api/users/' + id; return this.http.delete(url); } }
参考路由配置思路(课件abstract路由可不需要path):
const appRoutes: Routes = [ { path: 'compose', component: ComposeMessageComponent, outlet: 'popup' }, { path: 'admin', loadChildren: 'app/admin/admin.module#AdminModule', canLoad: [AuthGuard] }, { path: 'crisis-center', loadChildren: 'app/crisis-center/crisis-center.module#CrisisCenterModule', data: { preload: true } }, { path: '', redirectTo: '/superheroes', pathMatch: 'full' }, { path: '**', component: PageNotFoundComponent } ];
const adminRoutes: Routes = [ { path: '', component: AdminComponent, canActivate: [AuthGuard], children: [ { path: '', canActivateChild: [AuthGuard], children: [ { path: 'crises', component: ManageCrisesComponent }, { path: 'heroes', component: ManageHeroesComponent }, { path: '', component: AdminDashboardComponent } ] } ] } ];
const crisisCenterRoutes: Routes = [ { path: '', component: CrisisCenterComponent, children: [ { path: '', component: CrisisListComponent, children: [ { path: ':id', component: CrisisDetailComponent, canDeactivate: [CanDeactivateGuard], resolve: { crisis: CrisisDetailResolver } }, { path: '', component: CrisisCenterHomeComponent } ] } ] } ];