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