0

在页面下面的代码中显示 before-null-after,但控制台显示“2”。由于某种原因页面没有更新......我做错了什么?

import {Component, OnInit} from '@angular/core';
import {Http} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/map'


@Component({
  template: `before-{{searchResult | async | json}}-after`,
  selector: 'app-root',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {

  searchResult: Observable<String[]>;

  searchTerms = new Subject<String>();

  constructor(private http: Http) {

  }

  ngOnInit(): void {
    console.error(JSON.stringify(['aaaa', 'bbbb']));

    this.searchResult = this.searchTerms
      .switchMap(term => this.http.get('/assets/async.json').map(response => response.json() as String[]));
    this.searchResult.subscribe(next => console.error(next.length));

    this.searchTerms.next('sss');
  }
}

“@angular/core”:“^4.0.0”

4

1 回答 1

0

代替

searchTerms = new Subject<String>();

利用

searchTerms = new ReplaySubject<String>(1);

其中数字表示订阅此 observable 时有多少已发出的值被缓存和发出

或者

searchTerms = new BehaviorSubject<String>('');

在 observable 始终记住最后发出的值的情况下,您必须给出一个初始值。

于 2018-02-12T15:06:25.743 回答