2017-08-02 40 views
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'); 
    } 
} 

“@角/芯”: “^ 4.0.0”

+1

当你运行'subject.next('sss')'没有从模板订阅 – yurzui

+0

例如,这将工作https://plnkr.co/edit/kKNHI7NKWsebWmhl32mx?p=preview和'publishReplay'可以也帮助https://plnkr.co/edit/IOuzGaIcROVnu4fcOhLc?p=preview – yurzui

+0

是的,我明白这个问题。我实际上在订阅this.route.queryParamMap.subscribe()的代码中运行next()方法。有没有一种方法来观察queryParam并在模板中显示它?我想更改url params作为用户更新搜索,然后我想对结果作出反应。它工作正常,但不是在第一次加载页面时。 –

回答

0

代替

searchTerms = new Subject<String>();

使用

searchTerms = new ReplaySubject<String>(1);

其中数字指示如何许多已经发射的值被缓存和emi订阅此观察的

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

在观察的总是记住上次发射时的值tted,你必须给初始值。