Передайте объект в маршрутной ссылке Angular

привет, ребята, мне интересно, как передать объект в маршруте, когда я нажимаю на ссылку, например, в моем случае у меня есть страница с продуктами, и если я нажму на покупку, то будет перенаправлен на покупку моего компонента, передав полный объект продукта

Компонент дома

<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>

В моем ShopRoute.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);
    };
}

моя модель BasicProductData в basicproductdata.ts

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

person cesarpowerr20    schedule 07.03.2021    source источник


Ответы (1)


вы можете поместить объект в дополнительные услуги в маршруте

<p>
     <a type="button" class="btn btn-info botaoProduto" 
     [routerLink]="['/shop/purchase']" [state]="products">Purchase</a>
</p>

в компоненте покупки

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
    };
}
person pc_coder    schedule 07.03.2021
comment
спасибо, теперь проблема в том, что когда я пытаюсь передать объект продукта другому объекту внутри подписки, я получаю неопределенность. например, this.product = результат как продукт, здесь ОК, но когда я пытаюсь использовать this.tempProduct.name = this.product.name (this.tempProduct.name получает значение undefine при отладке) - person cesarpowerr20; 08.03.2021
comment
Можете ли вы поместить свой код также в компонент? в вопросе, то я вижу проблему. - person pc_coder; 08.03.2021
comment
привет pc_coder я обновил сообщение с дополнительной информацией о другой детали - person cesarpowerr20; 08.03.2021
comment
обновленный ответ, проверьте это. @cesarpowerr20 - person pc_coder; 08.03.2021
comment
большое спасибо, теперь все отлично - person cesarpowerr20; 08.03.2021