通过使用Http,我们调用一个执行网络调用并返回http observable的方法:
getCustomer() {
return this.http.get('/someUrl').map(res => res.json());
}
Run Code Online (Sandbox Code Playgroud)
如果我们采用这个可观察的并添加多个订阅者:
let network$ = getCustomer();
let subscriber1 = network$.subscribe(...);
let subscriber2 = network$.subscribe(...);
Run Code Online (Sandbox Code Playgroud)
我们想要做的是确保这不会导致多个网络请求.
这可能看起来像是一个不寻常的场景,但实际上很常见:例如,如果调用者订阅了observable以显示错误消息,并使用异步管道将其传递给模板,那么我们已经有两个订阅者.
在RxJs 5中这样做的正确方法是什么?
也就是说,这似乎工作正常:
getCustomer() {
return this.http.get('/someUrl').map(res => res.json()).share();
}
Run Code Online (Sandbox Code Playgroud)
但这是在RxJs 5中这样做的惯用方式,还是我们应该做其他事情呢?
注意:根据Angular 5 new HttpClient,.map(res => res.json())所有示例中的部分现在都没用,因为现在默认采用JSON结果.
根据食谱中的示例,我正在像这样动态创建组件:
private loadComponent(): void {
const componentFactory = this.factoryResolver.resolveComponentFactory(MyInputComponent);
const viewContainerRef = this.componentHost.viewContainerRef;
viewContainerRef.clear();
const componentRef = viewContainerRef.createComponent(componentFactory);
(<IComponent>componentRef.instance).data = data;
}
Run Code Online (Sandbox Code Playgroud)
MyInputComponent 的模板如下所示:
<input type="text" [(ngModel)]="data.inputProp">
Run Code Online (Sandbox Code Playgroud)
当用户输入输入时,我需要更新父级中 data.inputProp 的值。
我在一些例子中看到过这个,但不确定它有什么作用?
componentRef.changeDetectorRef.detectChanges();
Run Code Online (Sandbox Code Playgroud)
我还阅读了有关在父级中订阅子级 EventEmitter的内容,但只看到了使用单击事件的示例。将包括文本输入在内的各种数据更新回父级的更好方法是什么?
我正在使用 Angular 4 RC3