【问题标题】:Async pipe does not show my observable异步管道不显示我的可观察的
【发布时间】:2018-02-12 23:06:25
【问题描述】:

在页面下方的代码中显示 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"

【问题讨论】:

  • 当你运行 subject.next('sss') 时,没有来自模板的订阅
  • 例如这将起作用 plnkr.co/edit/kKNHI7NKWsebWmhl32mx?p=previewpublishReplay 也可以帮助 plnkr.co/edit/IOuzGaIcROVnu4fcOhLc?p=preview
  • 是的,我明白这个问题。我实际上在订阅 this.route.queryParamMap.subscribe() 的代码中运行 next() 方法。有没有办法观察 queryParam 并在模板中显示它?我想在用户更新搜索时更改 url 参数,然后我想对结果做出反应。它工作正常,但不是在第一页加载期间。
  • publishReplay 没有帮助?
  • 谢谢,发现问题。我只是不使用 Observable 而只是 String[] 成员并将其填充到 subsribe 方法中。它会保留该值,直到加载模板。我以前很喜欢这段代码,但这行得通....

标签: angular angular-observable


【解决方案1】:

代替

searchTerms = new Subject&lt;String&gt;();

使用

searchTerms = new ReplaySubject&lt;String&gt;(1);

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

searchTerms = new BehaviorSubject&lt;String&gt;('');

observable 总是记住最后发出的值,你必须给出一个初始值。

【讨论】:

    猜你喜欢
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 2019-01-04
    • 2016-08-14
    • 2021-08-18
    • 2018-08-06
    • 1970-01-01
    相关资源
    最近更新 更多