Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 访问路线参数-角度8_Angular_Routes_Angular8_Route Parameters - Fatal编程技术网

Angular 访问路线参数-角度8

Angular 访问路线参数-角度8,angular,routes,angular8,route-parameters,Angular,Routes,Angular8,Route Parameters,嘿,我试图用产品建立网站,但我无法从productsComponent到ProductDetailsComponent获取数据。请帮帮我 在我的Product.ts中,我有: export class Product { id: number; name: string; constructor(id: number, name: string) { this.id = id; this.name = name; } } 在我的ProductsCompo

嘿,我试图用产品建立网站,但我无法从productsComponent到ProductDetailsComponent获取数据。请帮帮我

在我的Product.ts中,我有:

    export class Product {
  id: number;
  name: string;
  constructor(id: number, name: string) {
    this.id = id;
    this.name = name;
  }
}
在我的ProductsComponenet中,我有:

    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")
  ];
}
在我的ProductDetail组件中:

    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;
        }
      });
    });
  }
}

我在products.html中显示每个产品,单击任何产品后,它会将我的productdetails.html与我的产品一起呈现,但不显示正确的名称和id。它显示每个产品中的第一个产品,但链接与产品的id是正确的。请帮忙。我真的搞不清楚到底发生了什么。

要直接解决您的问题,您需要执行以下操作:

this.route.paramMap.subscribe(params => {
   let id = params.get('id');
   this.product = this.products.find(product => product.id === +id);
})
请注意,路由参数始终是字符串,因此在上面的代码段中,我将在
find
方法中将id转换为一个数字

但是,我建议您避免完全明确订阅。下面,我将描述一个更易于维护的实现,它更紧密地遵循了反应式范例,并且我已经包括了一个正在工作的stackblitz示例

您可以通过管道连接到
paramMap
observable以获取路由参数,使用
switchMap
操作员订阅该参数,并使用产品服务按id获取产品

您的product-detail.component.ts如下所示:

@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);
      })
    )
  }

}

对于一个工作示例,请查看。

Id建议添加一个服务来抽象获取/设置/查找产品。您可以发布您为此模块创建的路由吗?我的路由是:const routes:routes=[{path:'',redirectTo:'home',pathMatch:'full'},{path:'home',component:HomeComponent},{path:'product/:id',component:DetailServiceComponent},];可能这是一个很长的解决方案,可以尝试使用params.get('id')而不是params.id来访问id。还可以尝试将this.routes.params订阅移动到构造函数。非常感谢。这个解决方案帮助了我!@valery很棒!很高兴提供帮助!
<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>