Angular:为<select>设置选定的值

Dan*_*cal 4 javascript rxjs typescript angular angular-forms

我有<select>异步加载的数据集.我使用hot observable,因为数据可以及时改变.问题是我无法设置选定的值,并且Angular也没有指向第一个元素(在用户执行之前没有设置值).我正在尝试订阅我自己的观察结果......它不起作用,我想知道为什么?我怎么解决这个问题?

PLNKR:https://plnkr.co/edit/uDmTSHq4naYGUjjhEe5Q

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
    <select [(ngModel)]="selectedValue">
      <option *ngFor="let value of (values$ | async)"
              [value]="value">{{ value }}
      </option>
    </select>
  `,
})
export class App implements OnInit, OnDestroy {
  public name: string;
  public selectedValue: string = '';
  public values$: Observable<Array<string>> = new Observable(observer => this.observer = observer);
  protected observer: Subscriber<Array<string>>;
  protected subscription: Subscription;

  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

  ngOnInit() {
    this.subscription = this.values$.subscribe((values) => {
      console.log('never fired...');
      this.selectedValue = values[0];
    });

    setTimeout(() => {
      this.observer.next(['some', 'test', 'data']);
    });
  }

  ngOnDestroy() {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

yur*_*zui 6

您订阅了两次您的观察.订阅后异步管道在内部执行.

当subscribe方法正在执行时,它执行subscribe函数

observer => this.observer = observer
Run Code Online (Sandbox Code Playgroud)

并覆盖this.observer属性,因此它只对异步管道(最后一个订阅者)有效

我会用share运算符来解决它

new Observable(observer => this.observer = observer).share();
Run Code Online (Sandbox Code Playgroud)

Plunker示例

要查看为什么this.observer被覆盖,只需运行此代码即可

let myObserver;   

const observable$ = new Rx.Observable(function subscribe(observer) {
  console.log('subscribe function has been called');
  myObserver = observer;
}); 

observable$.subscribe(function next1() { console.log('next1'); });
observable$.subscribe(function next2() { console.log('next2'); });
observable$.subscribe(function next3() { console.log('next3'); });

myObserver.next();
Run Code Online (Sandbox Code Playgroud)

jsbin.com

正如我所提到的,早期的异步管道在内部订阅了observable

https://github.com/angular/angular/blob/4.3.x/packages/common/src/pipes/async_pipe.ts#L23