2017-08-02 48 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,你必須給初始值。