Angular 5 - 如何在不刷新页面的情况下观看兄弟组件之间的数据更改?

问题描述 投票:0回答:2

我有两个兄弟组件,第一个组件有select盒,不同的option绑定到一个名为selectedValue的变量。当我更改第一个组件中的选项值时,我希望在第二个组件中更改相同的值。但是,第二个组件仍然显示未定义的值。这两个兄弟组件同时有ngOnInit

这是我的代码:

component1.ts:

selectedValue: any;
tokens: Tokens;

  constructor(
    private apiService: ApiService,
    private sharedService: SharedService
  ) {
  }

  ngOnInit() {
    this.loadTokens();
    this.sharedService.pair.next(this.selectedValue);
  }

  loadTokens() {
    this.apiService.getTokens()
    .subscribe((data: any) => {
      this.tokens = data;
    }, error => {
      console.log(error);
    });
  } 

component1.html:

<mat-select placeholder="Choose a pair" [(ngModel)]="selectedValue">
  <mat-option>-- None --</mat-option>
  <mat-option *ngFor="let token of tokens" [value]="token.shortName">
    {{token.name}}
  </mat-option>        
</mat-select>

shared.service.ts:

@Injectable()
export class SharedService {

  pair = new BehaviorSubject(null);

  observable: Observable<any> = this.pair.asObservable();
}

component2.ts:

pair: any;

  constructor(private sharedService: SharedService) {}

  ngOnInit() {
    this.sharedService.observable.subscribe((data) => {
      this.pair = data;
      console.log(this.pair);
    });
  }
angular
2个回答
3
投票

问题是你在设置值之前调用.next。你应该做的是:

<mat-select placeholder="Choose a pair" [(ngModel)]="selectedValue" (ngModelChange)="emit($event)"></mat-select>

emit(selectedValue) {
  this.sharedService.pair.next(selectedValue);
}

1
投票

您应该在每次更改时发送新的selectedValue值。例如component1.html:

<mat-select placeholder="Choose a pair" 
            (ngModelChange)="this.sharedService.pair.next($event);"
            [(ngModel)]="selectedValue">
  <mat-option>-- None --</mat-option>
  <mat-option *ngFor="let token of tokens" [value]="token.shortName">
    {{token.name}}
  </mat-option>        
</mat-select>

或者,而不是observables,在服务上创建字段pair: string并将其绑定到ngModel。 component1:[(ngModel)]="sharedService.pair" component2:{{sharedService.pair}}

© www.soinside.com 2019 - 2024. All rights reserved.