angular 路由傳參

spfLinux發表於2018-01-23

cart.component.ts

import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router'

@Component({
    selector: 'cart',
    template: `
        <h1>購物車頁面</h1>
        <button (click)="handleClick()">去結算</button>
        <a routerLink="/myOC/333">去結算</a>
    `
})

export class CartComponent implements OnInit {
    constructor(private myRouter:Router) { }

    ngOnInit() { }

    handleClick(){
        this.myRouter.navigateByUrl('myOC/123');
    }
}
orderconfirm.component.ts

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

@Component({
    selector: 'orderconfirm',
    template: `
        <h1>訂單確認頁面</h1>
        <p>價格:{{price}}</p>
    `
})

export class OrderConfirmComponent implements OnInit {
    price:number=0;
    constructor(private myAR:ActivatedRoute) { }

    ngOnInit() {
        this.myAR.params.subscribe((result)=>{
            console.log(result.price);
            this.price=result.price;
        })
    }
}

app.router.ts

import {CartComponent} from './demo16/cart.component';
import {OrderConfirmComponent} from './demo16/orderconfirm.component';
{ path: 'myOC/:price', component: OrderConfirmComponent},

最後還需要在app.module.ts加些配置就好。

相關文章