我正在尝试Angular2.
我注意到http服务使用Observable对象而不是Promise(我不喜欢那个选择.. async/ await正在到达).
在我的服务中,我Plants从webservice 下载了一个列表.单击工厂我使用路由显示详细信息.但是当我回去的时候,再次下载植物(因为再次调用构造函数).
为了避免这种情况,我想做类似的事情:
public getPlants(): Observable<Plants[]>
{
if (this._plants != null)
return Observable.fromResult (this._plants); //This method does not exists
return this._http.get('../../res/heroes.json')...
}
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?如何Observable在ts文件中导入该类?
谢谢!
我试图通过迁移当前用Angular1编写的应用程序来提高我对Angular2的了解
特别令我难过的一个特点.我试图复制一个功能,其中一个调用函数等待继续,直到它调用的函数完成了一个promises循环.在有角度的一个中,我调用的函数看起来基本上是这样的:
this.processStuff = function( inputarray, parentnodeid ) {
var promises = [];
var _self = this;
angular.forEach( inputarray , function( nodeid ) {
switch ( parentnodeid )
{
case ‘AAA’ : var component = _self.doMoreStuff( nodeid, parentnodeid ); break;
case ‘BBB’ : var component = _self.doMoreStuff( nodeid, parentnodeid ); break;
case ‘CCC’ : var component = _self.doMoreStuff( nodeid, parentnodeid ); break;
default : var component = null;
}
promises.push( component );
});
return $q.all(promises);
};
Run Code Online (Sandbox Code Playgroud)
它包含一个forEach循环,它调用另一个函数(doMoreStuff),该函数也返回一个promise,它将所有返回的promises存储在一个数组中.
使用Angular1,当我在另一个函数中调用processStuff时,我可以指望系统等到processStuff完成后再进入then块中的代码.IE:
service.processStuff( arraying, …Run Code Online (Sandbox Code Playgroud) 我有两个需要通过服务共享数据的Angular2组件:
@Injectable()
export class SearchService {
private searchResultSource = new Subject<string>()
searchResult$ = this.searchResultSource.asObservable()
setSearchResults(_searchResult: string): void {
this.searchResultSource.next(_searchResult)
}
}
Run Code Online (Sandbox Code Playgroud)
假设ComponentA已呈现并且它通过发出事件SearchService.setSearchResults.然后用户导航到ComponentB,也订阅searchResult$.但是,ComponentB永远不会观察发出的事件,ComponentA因为它searchResult$在ComponentA发出事件时没有订阅,因为它不存在.
如何创建Observable向每个新订阅者发送最后一个事件的内容?
我用这个方法构建了一个简单的确认对话服务(Angular 2):
confirm(body?: string, title?: string): Subject<void> {
this.confirmation = new Subject<void>();
// ... show dialog here... "are you sure?"
return this.confirmation;
}
_onYesClicked() {
// ... closing the dialog
this.confirmation.next();
this.confirmation.complete();
}
_onNoClicked() {
// ... closing the dialog
this.confirmation.complete();
}
Run Code Online (Sandbox Code Playgroud)
用法:
confirmationService.confirm().subscribe(() => alert("CONFIRMED"));
Run Code Online (Sandbox Code Playgroud)
如果有人使用该服务,他会返回一个Subject(这是一个Observable),并且可以"订阅()".点击"是"时调用订阅,因此确认给出了...
这是正确的方法吗?更重要的是...将致电
this.confirmation.complete();
Run Code Online (Sandbox Code Playgroud)
取消订阅订阅的侦听器,从而防止任何延迟引用(内存泄漏)?
我想显示一个可编辑的项目列表,每个项目都是可编辑的(在某种程度上类似于可编辑的网格).我正在使用KnockoutJS.我不能只使用一个简单的Observable Array,因为文档声明"一个observableArray跟踪数组中的哪些对象,而不是那些对象的状态"
因此,我创建了一个observableArray的可观察对象(使用utils.arrayMap),并将它们绑定到视图.但问题是,如果我在屏幕上编辑数据,则用户在屏幕上进行的任何数据输入更改似乎都不会生效.见http://jsfiddle.net/AndyThomas/E7xPM/
我究竟做错了什么?
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.0.0/knockout-min.js" type="text/javascript"></script>
<table>
<tbody data-bind="template: { name:'productListJavascriptTemplate', foreach: products}">
</tbody>
</table>
<script type="text/html" id="productListJavascriptTemplate">
<tr>
<td>Name: <input data-bind="value: Name"/></td>
<td>Name: <span data-bind="text: Name"/></td>
<td><select data-bind="options: this.viewModel.categories,
optionsText: 'Name', optionsValue: 'Id', value: CategoryId,
optionsCaption: 'Please select...'"></select></td>
<td>CategoryId: <input data-bind="value: CategoryId"/></td>
</tr>
</script>?
var categoryList= [
{
Name: "Electronics",
Id: "1"},
{
Name: "Groceries",
Id: "2"}
];
var initialData= [
{
Name: "Television",
CategoryId: "1"},
{
Name: "Melon",
CategoryId: "2"}
];
var viewModel = {
products: …Run Code Online (Sandbox Code Playgroud) RxJava最近推出了Single.有没有办法将已经存在的Observable(几乎是单个)转换为Single而不修改原始observable的源?
例如,我有一个api服务类,其中包含一个返回Observable的方法 - 它本质上是从远程资源中获取用户.说我无法修改服务.我想在其他地方消费,但返回单身.我该怎么做呢?
捏更多的背景
RxJava最近引入了Single的概念,它或多或少是一个Rx友好的简单回调(即一个Observable发出一个对象或一个错误)(在这里阅读更多关于它 - http://reactivex.io/documentation/single.html)
我一直在试图解决这个问题,而且我已经能够阅读的任何文档都没有给我一个问题的答案.
我有一个直接与API通信并返回可观察事件的服务,在正常情况下我会订阅并按照数据执行我想要的操作,但是在使用来自restful服务的请求的辅助服务中,我需要能够从请求中返回值.
getSomething() {
return this._restService.addRequest('object', 'method').run()
.subscribe(
res => {
res;
},
err => {
console.error(err);
}
);
}
returnSomething() {
return this.getSomething();
}
Run Code Online (Sandbox Code Playgroud)
在上面的快速示例中,我想知道是否有任何方法可以res从getSomething()内部返回returnSomething().如果以这种方式无法实现,那么替代方案是什么?我将补充说,_restService非常依赖,我真的不想开始搞乱它.
我有这个代码
return this.http.get(this.pushUrl)
.toPromise()
.then(response => response.json().data as PushResult[])
.catch(this.handleError);
Run Code Online (Sandbox Code Playgroud)
我想用observable而不是Promise
我怎样才能将错误返回给调用方法?
相当于 Promise.reject什么?
doSomeGet() {
console.info("sending get request");
this.http.get(this.pushUrl)
.forEach(function (response) { console.info(response.json()); })
.catch(this.handleError);
}
private handleError(error: any) {
console.error('An error occurred', error);
// return Promise.reject(error.message || error);
}
}
Run Code Online (Sandbox Code Playgroud)
调用方法是:
getHeroes() {
this.pushService
.doSomeGet();
// .then(pushResult => this.pushResult = pushResult)
// .catch(error => this.error = error);
}
Run Code Online (Sandbox Code Playgroud) 我想实现一个Navigation View包含许多片段的片段,这些片段完全依赖于在中定义的值MainActivity.我知道MainActivity中的变量可以使用MainActivity中定义的方法从其他Fragments获取以获取值,但是这里的catch是MainActivity中变量的值可能会改变(在AsyncThread上运行).现在,我要么更改代码,以便我的Fragments根据片段本身中的某些事件更新其值或使用SharedPreference.但我不想使用SharedPreferences,也不必多次检查值的变化.
我知道在RxJS中,我们使用Observable以异步方式运行,并以类似于传送带的方式工作.通过官方文档进行了一些谷歌搜索:Observable证实了我对Android中可用的类似内容的怀疑,但找不到任何适当的教程或如何实现它的解释.所以,我正在寻找一个简单的代码片段,它可以清楚地说明Observable在Android中是如何工作的,如果它是Async,并且它的基础类似于它的RxJS实现.(不,我不想要RxJS实现)
测试用例:
MainActivity : int a, b (need observable for both variables)
Frag1 : int a1 , b1, a1changed(),b1changed()
Frag2 : int a2 , b2, a2Changed(), b2changed()
Run Code Online (Sandbox Code Playgroud)
MainActivity包含整数,其值在更改时应反映在片段中的相应整数中,并在注意到的更改上调用每个片段的单独函数.
我有这样的界面
export interface Details {
Name: [{
First: string;
Last: string;
}];
}
Run Code Online (Sandbox Code Playgroud)
我有一个可观察的配置变量
Configuration: KnockoutObservable<Details> = ko.observable<Details>();
Run Code Online (Sandbox Code Playgroud)
我想在构造函数中为它赋值如下 -
config = {
Name: [{
First: "ABC",
Last: "DEF"
},
{
First: "LMN",
Last: "XYZ"
}]
};
this.Configuration(config);
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
属性"名称"的类型不兼容,类型中缺少属性"0".
输入'{First:string; 最后:字符串; } []'不能赋值为'[{First:string; 最后:字符串; }]"
我无法控制更改界面,因为它在其他地方使用.初始化此配置变量的正确方法是什么?
提前致谢.
observable ×10
angular ×6
rxjs ×4
typescript ×4
javascript ×2
knockout.js ×2
android ×1
http ×1
java ×1
promise ×1
rx-java ×1