嘿试图用产品建立网站,但我无法从 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")
];
}
在我的 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;
}
});
});
}
}
我在 products.html 中显示每个产品,在我单击任何产品后,它会使用我的产品呈现我的 productdetails.html,但不显示正确的名称和 ID。IT 显示每个产品中的第一个,但链接与产品的 id 是正确的。请帮忙。我真的不知道发生了什么。