You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中点击按钮后如何向非父子组件传递产品模型数据

Angular非父子组件传递Product数据方案

方法一:使用共享服务(推荐)

这种方法适配组件同屏展示或路由跳转场景,核心靠全局共享服务传递数据。

  1. 创建共享服务
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { Product } from './product.model'; // 替换为你的Product类型定义

@Injectable({ providedIn: 'root' })
export class ProductService {
  // 用BehaviorSubject存储选中的产品,初始值为null
  private selectedProductSource = new BehaviorSubject<Product | null>(null);
  // 对外暴露可观察对象,防止外部直接修改数据源
  selectedProduct$ = this.selectedProductSource.asObservable();

  // 设置选中产品的方法
  setSelectedProduct(product: Product) {
    this.selectedProductSource.next(product);
  }
}
  1. 在Component A中调用服务传递数据
    Component A模板:
<ul>
  <li *ngFor="let product of products">
    {{ product.name }}
    <button (click)="viewProduct(product)">查看</button>
  </li>
</ul>

Component A逻辑:

import { Component } from '@angular/core';
import { ProductService } from './product.service';
import { Product } from './product.model';
import { Router } from '@angular/router'; // 需要跳转路由则导入

@Component({
  selector: 'app-component-a',
  templateUrl: './component-a.component.html'
})
export class ComponentAComponent {
  products: Product[] = [/* 你的产品数组数据 */];

  constructor(
    private productService: ProductService,
    private router: Router // 需要跳转路由则注入
  ) {}

  viewProduct(product: Product) {
    // 将选中的产品传给服务
    this.productService.setSelectedProduct(product);
    // 需要跳转到Component B的话,添加这行代码
    this.router.navigate(['/component-b']);
  }
}
  1. 在Component B中订阅服务获取数据并展示
    Component B模板:
<div *ngIf="selectedProduct">
  <h3>{{ selectedProduct.name }} 的项目列表</h3>
  <ul>
    <li *ngFor="let item of selectedProduct.items">{{ item.name }}</li>
  </ul>
</div>

Component B逻辑:

import { Component, OnInit } from '@angular/core';
import { ProductService } from './product.service';
import { Product } from './product.model';

@Component({
  selector: 'app-component-b',
  templateUrl: './component-b.component.html'
})
export class ComponentBComponent implements OnInit {
  selectedProduct: Product | null = null;

  constructor(private productService: ProductService) {}

  ngOnInit() {
    // 订阅服务的产品数据,更新组件内变量
    this.productService.selectedProduct$.subscribe(product => {
      this.selectedProduct = product;
    });
  }
}

方法二:使用路由参数传递(适合路由跳转场景)

如果Component B是通过路由打开的,可以传递产品ID,再根据ID获取完整产品数据。

  1. 配置路由
    在app-routing.module.ts中添加Component B的路由:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ComponentBComponent } from './component-b.component';

const routes: Routes = [
  // ...其他路由配置
  { path: 'component-b/:productId', component: ComponentBComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}
  1. Component A中跳转路由并传递ID
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Product } from './product.model';

@Component({
  selector: 'app-component-a',
  templateUrl: './component-a.component.html'
})
export class ComponentAComponent {
  products: Product[] = [/* 你的产品数组数据 */];

  constructor(private router: Router) {}

  viewProduct(product: Product) {
    // 跳转到Component B的路由,同时传递产品ID
    this.router.navigate(['/component-b', product.id]);
  }
}
  1. Component B中获取路由参数并加载产品数据
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ProductService } from './product.service';
import { Product } from './product.model';

@Component({
  selector: 'app-component-b',
  templateUrl: './component-b.component.html'
})
export class ComponentBComponent implements OnInit {
  selectedProduct: Product | null = null;

  constructor(
    private route: ActivatedRoute,
    private productService: ProductService // 假设服务中有获取单个产品的方法
  ) {}

  ngOnInit() {
    // 监听路由参数变化
    this.route.paramMap.subscribe(params => {
      const productId = params.get('productId');
      if (productId) {
        // 同步数据直接根据ID获取产品
        this.selectedProduct = this.productService.getProductById(Number(productId));
        // 异步请求(比如HTTP接口)则用subscribe处理:
        // this.productService.getProductById(Number(productId)).subscribe(product => {
        //   this.selectedProduct = product;
        // });
      }
    });
  }
}

内容的提问来源于stack exchange,提问作者Danny Jebb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 03:05:49