【问题标题】:Angular 5 - How to watch data change between sibling components without refreshing page?Angular 5 - 如何在不刷新页面的情况下观察兄弟组件之间的数据变化?
【发布时间】:2018-08-12 22:18:06
【问题描述】:

我有两个同级组件,第一个组件有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);
    });
  }

【问题讨论】:

  • ngOnChanges 帮助您检测任何输入更改
  • hmm,我之前没用过,你知道有demo或者参考链接吗?谢谢
  • ngdev.space/… 试试这个

标签: angular


【解决方案1】:

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

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

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

【讨论】:

  • 组件 2 中仍未定义 :(
【解决方案2】:

您应该在每次更改时发送新的selectedValue 值。 例如 组件1.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。 组件1: [(ngModel)]="sharedService.pair" 组件2: {{sharedService.pair}}

【讨论】:

  • 酷,我明白你的意思,它应该按照你的建议工作。谢谢。
猜你喜欢
  • 2020-02-24
  • 1970-01-01
  • 2019-10-09
  • 1970-01-01
  • 2018-02-13
  • 1970-01-01
  • 2021-01-04
  • 2020-02-16
相关资源
最近更新 更多