Resove守衛

Phoenix_99發表於2020-10-05

product TS

import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Params, RouterLinkActive} from '@angular/router';

@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {

  public productId: number;
  public productName: string;
  constructor(private  routerInfo: ActivatedRoute) { }

  ngOnInit(): void {
    this.routerInfo.params.subscribe((params: Params) => this.productId = params.id);
    this.routerInfo.data.subscribe((data: {product: Product}) => {
      this.productId = data.product.id;
      this.productName = data.product.name;
    });
    // this.productId = this.routerInfo.snapshot.params["id"];
  }
}

export class Product {
  // tslint:disable-next-line:typedef
  constructor(public id: number,public name: string){
  }
}

2.product.resoved.ts

import {ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot} from '@angular/router';
import {Observable} from 'rxjs';
import {Product, ProductComponent} from '../product/product.component';
import {Injectable, Injector} from '@angular/core';

// @ts-ignore
@Injectable()
export class ProductResoved implements Resolve<Product> {
    constructor(private  router: Router) {
    }
  // tslint:disable-next-line:max-line-length
    resolve(route: ActivatedRouteSnapshot){
      //  const productId: number = route.params.id;
        let productId: number = route.params["id"];

        if (productId == 2){
          return new Product(productId, "iPhone8 Plus");
        }else{
          this.router.navigate(['/home']);
          return undefined;
        }
    }
}

3.app-routing

const routes: Routes = [
  {path: '', redirectTo: '/home', pathMatch: 'full'},
  {path: 'home', component: HomeComponent},
  {path: 'chat', component: ChatComponent, outlet: 'talkroom'},
  {path: 'product/:id', component: ProductComponent, children: [
     {path: '', component: ProductDescComponent},
     {path: 'sellerID/:id', component: SellerInfoComponent}
    ], resolve: {
    product: ProductResoved
    }
  },
  {path: '**', component: Code404Component},
];

4.product HTML

<div class="product">
<p>這裡是商品資訊元件!</p>
<p>商品ID是{{productId}}</p>
<p>商品名稱是 {{productName}}</p>
<a [routerLink]="['./']">商品描述  </a>
<a [routerLink]="['./sellerID',9]">銷售員資訊</a>
<router-outlet></router-outlet>
</div>

 

相關文章