在Angular的路由链接中传递对象



嗨,我想知道如何在路由中传递一个对象,当我点击链接时,例如,在我的情况下,我有一个产品页面,如果我点击"purchase",然后将被重定向到我的组件购买,传递完整的产品对象

HomeComponent

<div class="container main-container
<ul  class="nav product-list">
<li *ngFor="let products of product" >
<div class="card">
<img src="{{products.Image}}" alt="Denim Jeans" style="width:100%;height:250px;">
<h1>{{products.name}}</h1>
<p class="price">€ {{products.price}} </p>
<p><a type="button" class="btn btn-info botaoProduto" [routerLink]="['/shop/purchase',objecProducttHere]">Purchase</a></p>
</div>
</li>
</ul> 
</div>
<script>
</script>

在我的shoproutes .ts

const shopRoutingConfig:Routes = [
{
path:'',component:ShopAppComponent,
children:[
{path:'purchase/objectproduct',component:PurchaseCompoet}
]
}
]

@NgModule({
imports:[
RouterModule.forChild(shopRoutingConfig)
],
exports:[RouterModule],
})
export class ShopRoutingModule{}

product:Product;
tempData:BasicproductData;
ngOnInit() {
if(this.obterUsuarioLogado())
{
this.router.events.pipe(
filter(e => e instanceof NavigationStart),
map(() => this.router.getCurrentNavigation().extras.state)
).subscribe(result=>{ 
this.product = result as Product //here product object its fine
this.tempData.id = this.product.id; // here, even product object filled, tempData receive undefinned
this.tempData.name = this.product.name;//same here problem here
console.log(this.tempData);
console.log( this.product);

},
error=> this.errorMessage);
//this.sendOrder(this.tempData);
};
}

my model BasicProductData in BasicProductData .ts

export class BasicProductData
{
id:strring;
name:string;
}

你可以在路由

中添加额外的对象
<p>
<a type="button" class="btn btn-info botaoProduto" 
[routerLink]="['/shop/purchase']" [state]="products">Purchase</a>
</p>

in purchase component

product:Product;
tempData:BasicproductData;
ngOnInit() {
if(this.obterUsuarioLogado())
{
this.router.events.pipe(
filter(e => e instanceof NavigationStart),
map(() => this.router.getCurrentNavigation().extras.state)
).subscribe(result=>{ 
this.product = result as Product //here product object its fine
this.tempData=new BasicproductData();
this.tempData.id = this.product.id; // here, even product object filled, tempData receive undefinned
this.tempData.name = this.product.name;//same here problem here
console.log(this.tempData);
console.log( this.product);
this.sendOrder(this.tempData);
},
error=> this.errorMessage);
// you cant reach outside of subscribe this is async
};
}

相关内容

  • 没有找到相关文章

最新更新