在共享服务中创建一个 Subject 或 BehaviorSubject,并从一个兄弟组件中订阅该主体。然后在子组件中更改参数,并使用 next() 方法将新值推送到被订阅的 Subject 或 BehaviorSubject。这样,兄弟组件将收到参数值的更新并进行相应的更改。
共享服务示例代码:
import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SharedService {
private _paramValue$ = new BehaviorSubject
get paramValue$() { return this._paramValue$.asObservable(); }
public updateParamValue(newValue: string) { this._paramValue$.next(newValue); } }
在兄弟组件中订阅 paramValue$:
import { Component, OnInit } from '@angular/core'; import { SharedService } from '../services/shared.service';
@Component({
selector: 'app-sibling1',
template: Parameter value: {{ paramValue }}
})
export class Sibling1Component implements OnInit {
paramValue: string;Sibling 1 Component
constructor(private sharedService: SharedService) {}
ngOnInit() { this.sharedService.paramValue$.subscribe((value) => (this.paramValue = value)); } }
在子组件中更改参数并推送更新:
import { Component, OnInit } from '@angular/core'; import { SharedService } from '../services/shared.service';
@Component({
selector: 'app-child',
template:
})
export class ChildComponent {
constructor(private sharedService: SharedService) {}
update() { this.sharedService.updateParamValue('New parameter value'); } }
在兄弟组件中,通过 @Input() 将参数值传递给子组件,并在子组件中更改参数值,并使用 @Output() 将新值传递回兄弟组件。这样,兄弟组件将收到更新的参数值并进行相应的更改。
示例代码:
在父组件中使用子组件和兄弟组件:
兄