Angular4中如何将ID从一个同级组件传递至另一个同级组件?
Hey there! Let's work through how to pass an ID between your sibling components (TripDetailsComponent and CreateExpenseComponent) in Angular 4. Looking at your routing setup, both are child routes under HomeComponent, so here are two practical, widely-used approaches to get this done:
1. Pass ID via Route Parameters (Best for URL-Visible Data)
Since your create-expense route already defines a :id parameter, you can simply pass the ID when navigating from TripDetailsComponent to CreateExpenseComponent.
Step 1: Add Navigation Logic in TripDetailsComponent
First, inject the Router service and create a method to handle the navigation:
import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-trip-details', templateUrl: './tripDetails.component.html' }) export class TripDetailsComponent { tripId: string; // Assume this holds your trip ID, fetched from API or elsewhere constructor(private router: Router) {} navigateToCreateExpense() { // Pass the trip ID as a route parameter this.router.navigate(['/home/create-expense', this.tripId]); } }
Step 2: Bind the Method to Your Button
Update your button in tripDetails.component.html to trigger the navigation:
<button class="btn btn-primary" (click)="navigateToCreateExpense()">Create New Expense</button>
Step 3: Retrieve the ID in CreateExpenseComponent
Use ActivatedRoute to subscribe to the route parameters and get the ID:
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-create-expense', templateUrl: './createExpense.component.html' }) export class CreateExpenseComponent implements OnInit { tripId: string | null; constructor(private route: ActivatedRoute) {} ngOnInit() { // Subscribe to param changes (handles case where user navigates directly) this.route.paramMap.subscribe(params => { this.tripId = params.get('id'); console.log('Trip ID received:', this.tripId); // Use the ID for your expense creation logic here }); } }
2. Share ID via a Shared Service (Best for Non-URL Data)
If you don't want the ID visible in the URL, or need to share additional data between components, use a shared service with RxJS BehaviorSubject (perfect for Angular 4's RxJS v5 setup).
Step 1: Create a Shared Service
Generate a service (e.g., TripDataService) to hold and emit the trip ID:
import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; @Injectable() export class TripDataService { // BehaviorSubject retains the latest value for new subscribers private tripIdSource = new BehaviorSubject<string | null>(null); currentTripId = this.tripIdSource.asObservable(); constructor() {} // Method to update the trip ID setTripId(id: string) { this.tripIdSource.next(id); } }
Don't forget to add this service to the providers array in your AppModule to ensure it's a singleton (one instance across the app).
Step 2: Set the ID in TripDetailsComponent
Inject the service and set the trip ID when needed (e.g., on button click or when the trip loads):
import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { TripDataService } from '../services/trip-data.service'; @Component({ selector: 'app-trip-details', templateUrl: './tripDetails.component.html' }) export class TripDetailsComponent { tripId: string; constructor( private router: Router, private tripDataService: TripDataService ) {} navigateToCreateExpense() { // Set the trip ID in the service first this.tripDataService.setTripId(this.tripId); // Navigate to the create expense route this.router.navigate(['/home/create-expense']); } }
Step 3: Retrieve the ID in CreateExpenseComponent
Subscribe to the service's observable to get the trip ID:
import { Component, OnInit } from '@angular/core'; import { TripDataService } from '../services/trip-data.service'; @Component({ selector: 'app-create-expense', templateUrl: './createExpense.component.html' }) export class CreateExpenseComponent implements OnInit { tripId: string | null; constructor(private tripDataService: TripDataService) {} ngOnInit() { this.tripDataService.currentTripId.subscribe(id => { this.tripId = id; if (this.tripId) { console.log('Trip ID received from service:', this.tripId); // Proceed with your expense creation logic } }); } }
Which Approach Should You Choose?
- Use route parameters if you want the ID to be part of the URL (so users can bookmark the create expense page with the trip context).
- Use a shared service if you prefer not to expose the ID in the URL, or need to share more complex data between components.
内容的提问来源于stack exchange,提问作者VIK6Galado

