简体   繁体   中英

Accessing route parameters - angular 8

Hey trying to build website with products, but i can't get data from productsComponent to ProductDetailsComponent. Please help me.

In my Product.ts i have :

    export class Product {
  id: number;
  name: string;
  constructor(id: number, name: string) {
    this.id = id;
    this.name = name;
  }
}

In my ProductsComponenet i have:

    import { Component } from '@angular/core';
import { Product } from '../services.service';

@Component({
  selector: 'app-services',
  templateUrl: './services.component.html',
  styleUrls: ['./services.component.css']
})
export class ServicesComponent {
  public products: Product[] = [
    new Product(1, "Product 001"),
    new Product(2, "Product 002"),
    new Product(3, "Product 003"),
    new Product(4, "Product 004"),
    new Product(5, "Product 005"),
    new Product(6, "Product 006"),
    new Product(7, "Product 007"),
    new Product(8, "Product 008")
  ];
}

And in my ProductDetailComponent:

    import {Component, OnInit} from '@angular/core';
import { ActivatedRoute} from '@angular/router';
import { Product } from '../services.service';



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

  public products: Product[] = [
    new Product(1, "Product 001"),
    new Product(2, "Product 002"),
    new Product(3, "Product 003"),
    new Product(4, "Product 004"),
    new Product(5, "Product 005"),
    new Product(6, "Product 006"),
    new Product(7, "Product 007"),
    new Product(8, "Product 008")
  ];
  product: Product = this.products[0];

  constructor(private routes: ActivatedRoute) {}
  ngOnInit() {
    this.routes.params.subscribe(params => {
      this.products.forEach((p: Product) => {
        if (p.id === params.id) {
          this.product = p;
        }
      });
    });
  }
}

I show every products in products.html and after i click on any product it renders my productdetails.html with my product, but don't show proper name and id. IT shows first one in every product, but link is proper with id of the product. PLease help. I really can't figure out what is going on.

To solve your problem directly, you want to do something like:

this.route.paramMap.subscribe(params => {
   let id = params.get('id');
   this.product = this.products.find(product => product.id === +id);
})

Note that route parameters are always strings, so in the snippet above, I'm converting the id to a number in the find method.

I would recommend that you avoid subscribing explicitly altogether, however. Below, I describe a more maintainable implementation that follows the reactive paradigm more closely and I've included a working stackblitz example.

You would pipe onto the paramMap observable to get your route parameter, subscribe to it with the switchMap operator, and use a product service to get the product by id.

Your product-detail.component.ts would look like this:

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

  product$: Observable<any>;

  constructor(
    private route: ActivatedRoute,
    private productService: ProductService
  ) { }

  ngOnInit() {
    this.product$ = this.route.paramMap.pipe(
      switchMap(params => {
        let id = params.get('id');
        return this.productService.getProductById(+id);
      })
    )
  }

}

Note that the pipe doesn't execute until we subscribe to it. We should use the async pipe for that. So your product-detail.component.html should look like:

<div class="product-detail-wrapper" *ngIf="product$ | async as product">
  <h3>Product Detail</h3>
  <p>Product ID: {{ product.id }}</p>
  <p>Product Name: {{ product.name }}</p>
</div>

For a working example, check out this stackblitz .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM