异步管道不显示我的可观察性

时间:2017-08-02 19:37:24

标签: angular angular-observable

在下面的代码页面显示之前的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”

1 个答案:

答案 0 :(得分:0)

而不是

searchTerms = new Subject<String>();

使用

searchTerms = new ReplaySubject<String>(1);

其中数字表示订阅此可观察量时缓存和发出的已发射值的数量

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

当observable始终记住最后一次发射的值时,你必须给出一个初始值。