import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from "@angular/router"; import { Product } from "../product/product.component"; import { Observable } from "rxjs/Observable"; import { Injectable } from "@angular/core"; @Injectable() export class ProductResolve implements Resolve<Product> { constructor(private router: Router) { } resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Product | Observable<Product> | Promise<Product> { let productId: number = route.params["id"]; if (productId == 1) { return new Product("pingguo7", 1); } else { this.router.navigate([‘/home‘]); return undefined; } } }
import { NgModule } from ‘@angular/core‘; import { Routes, RouterModule } from ‘@angular/router‘; import { HomeComponent } from ‘./home/home.component‘; import { ProductComponent } from ‘./product/product.component‘; import { Code404Component } from ‘./code404/code404.component‘; import { ProductDescComponent } from ‘./product-desc/product-desc.component‘; import { SellerInfoComponent } from ‘./seller-info/seller-info.component‘; import { ChatComponent } from ‘./chat/chat.component‘; import { LoginGuard } from ‘./guard/login.guard‘; import { UnsacedGuard } from ‘./guard/unsaced.guard‘; import { ProductResolve } from ‘./guard/product.resolve‘; const routes: Routes = [ { path: ‘‘, redirectTo: ‘/home‘, pathMatch: ‘full‘ }, { path: ‘chat‘, component: ChatComponent, outlet: ‘aux‘ }, { path: ‘home‘, component: HomeComponent }, { path: ‘product/:id‘, component: ProductComponent, children: [ { path: ‘‘, component: ProductDescComponent }, { path: ‘seller/:id‘, component: SellerInfoComponent } ], resolve: { product: ProductResolve } } , { path: ‘**‘, component: Code404Component } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], providers: [LoginGuard, UnsacedGuard, ProductResolve] }) export class AppRoutingModule { }
import { Component, OnInit } from ‘@angular/core‘; import { ActivatedRoute, Params } from ‘@angular/router‘; @Component({ selector: ‘app-product‘, templateUrl: ‘./product.component.html‘, styleUrls: [‘./product.component.css‘] }) export class ProductComponent implements OnInit { private productId: number; private productName: string; constructor(private routeInfo: ActivatedRoute) { } ngOnInit() { this.routeInfo.params.subscribe((params: Params) => this.productId = params["id"]); this.routeInfo.data.subscribe((data: { product: Product }) => { this.productId = data.product.id; this.productName = data.product.Name; }); //this.productId = this.routeInfo.snapshot.params["id"]; } } export class Product { constructor(public Name: string, public id: number) { } }
原文地址:https://www.cnblogs.com/chenyishi/p/8904172.html
时间: 2024-10-31 16:47:21