编辑:更新了Plunkr:http://plnkr.co/edit/fQ7P9KPjMxb5NAhccYIq?p = preview
这部分有效:
<div *ngFor="let entry of entries | async">
Label: {{ entry.label }}<br>
Value: {{ entry.value }}
</div>
Run Code Online (Sandbox Code Playgroud)
但我对选择框有问题,错误信息是:
无法绑定到'ngModel',因为它不是'select'的已知属性
整个组件:
//our root app component
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
import {HTTP_PROVIDERS, Http} from '@angular/http';
import 'rxjs/Rx';
import {Observable} from 'rxjs/Rx';
@Component({
selector: 'my-app',
providers: [HTTP_PROVIDERS],
template: `
<select [(ngModel)]="selectValue" name="selectValue">
<option *ngFor="let entry of entries | async"
[value]="entry.value">{{entry.label}}</option>
</select>
<div *ngFor="let entry of entries | async">
Label: {{ entry.label }}<br>
Value: {{ …Run Code Online (Sandbox Code Playgroud) json asynchronous drop-down-menu angular2-observables angular
this.service.service1().subscribe( res1 => {
this.service.service1().subscribe( res2 => {
this.service.service1().subscribe( res3 => {
this.funcA(res1, res2, res3);
});
});
});
Run Code Online (Sandbox Code Playgroud)
我需要将三个数据从三个不同的API传递给一个函数.
在订阅中订阅是一种好习惯吗?
如果没有,请建议最佳方式.
我在我的应用程序中多次这样做了.它很简单,它应该工作......但这次它没有.
我的问题:
我在组件A中调用服务中的方法,我的组件B已订阅但不响应也不接收任何内容.subscribe()没有触发!
导航elements.service.ts
@Injectable()
export class NavigationElementsService {
updateIBOsNavigation$: Observable<any>;
private updateIBOsNavigationSubject = new Subject<any>();
constructor() {
this.updateIBOsNavigation$ = this.updateIBOsNavigationSubject.asObservable();
}
updateIBOsNavigation(navigationData) {
log.d('updateIBOsNavigation', JSON.stringify(navigationData));
this.updateIBOsNavigationSubject.next(navigationData);
}
}
Run Code Online (Sandbox Code Playgroud)
IboDetailsGeneral 零件
export class IboDetailsGeneral implements OnInit, OnDestroy {
id: string;
private sub: any;
constructor(private route: ActivatedRoute, private iboService: IBOsService, private navigationService: NavigationElementsService) {
this.sub = this.route.params.subscribe(params => {
this.id = params['id'];
console.log('CALLING updateIBOsNavigation FUNCTION');
this.navigationService.updateIBOsNavigation(this.id);
});
}
ngOnInit() {
console.log('CALLING updateIBOsNavigation FUNCTION AGAIN');
this.navigationService.updateIBOsNavigation('test');
}
ngOnDestroy() {
this.sub.unsubscribe(); …Run Code Online (Sandbox Code Playgroud) 在我的页面中有一个生成报告的按钮.该报告需要在加载页面时使用http调用加载到休息端点的数据,但我无法保证在用户按下报告按钮时加载它们.
如何观察观察结果是否完整,如果不完整,等待动作直到http呼叫完成?以下是一些代码:
loadCompanies(): void {
this._companyService.getCompanies().subscribe(
response => {
this.companiesModel = response;
},
err => console.log(err)
);
}
Run Code Online (Sandbox Code Playgroud)
generateReport() {
// check if observable that loads companies is completed and do the
// action using companiesModel.
}
Run Code Online (Sandbox Code Playgroud)
一个选项是在加载公司中设置标志,其值为"loading"和"completed",并等待generateReport()标志完成,但我希望Observable尽可能使用API 的解决方案.
我需要在一个间隔中刷新组件页面中的数据.此外,我需要在执行某些操作后刷新数据.我在服务中使用Obeservables,以便我可以在响应准备好时订阅.我正在推送对象的订阅,以便我可以清除它ngDestroy,我认为,我有以下方法来实现相同的目标.
方法1:setInterval
我已经设置了一个间隔ngOnInit,它将以相等的间隔调用refreshData.将使用clearIntervalin ngOnDestroy方法清除interval对象.
export class MyComponent implements OnInit, OnDestroy {
private subscription: Subscription = new Subscription();
data: any;
interval: any;
ngOnInit() {
this.refreshData();
this.interval = setInterval(() => {
this.refreshData();
}, 5000);
}
ngOnDestroy() {
this.subscription.unsubscribe();
clearInterval(this.interval);
}
refreshData(){
this.subscription.add(
this.myService.getData()
.subscribe(data => {
this.data = data;
})
);
}
doAction(){
this.subscription.add(
this.myService.doAction()
.subscribe(result => {
if(result === true){
this.refreshData();
}
})
);
}
}
Run Code Online (Sandbox Code Playgroud)
Q1:在每次刷新调用时subscription,都会向对象添加一个订阅,这会增加内存使用量,如果用户保持页面打开一段时间,浏览器可能会崩溃吗?
方法2:Observable.timer
此方法使用将在刷新数据后创建的计时器.
export class MyComponent …Run Code Online (Sandbox Code Playgroud) memory-leaks subscriptions setinterval angular2-observables angular
我有一个角度为2的组件,它响应路由参数的变化(组件不会从头开始重新加载,因为我们没有移出主路径.这是组件代码:
export class MyComponent{
ngOnInit() {
this._routeInfo.params.forEach((params: Params) => {
if (params['area']){
this._pageToShow =params['area'];
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
这是一种享受,并_pageToShow适合导航.
我正在尝试测试路线变化的行为(所以这是可观察的第二个触发器,但它拒绝为我工作.)这是我的尝试:
it('sets PageToShow to new area if params.area is changed', fakeAsync(() => {
let routes : Params[] = [{ 'area': "Terry" }];
TestBed.overrideComponent(MyComponent, {
set: {
providers: [{ provide: ActivatedRoute,
useValue: { 'params': Observable.from(routes)}}]
}
});
let fixture = TestBed.createComponent(MyComponent);
let comp = fixture.componentInstance;
let route: ActivatedRoute = fixture.debugElement.injector.get(ActivatedRoute);
comp.ngOnInit();
expect(comp.PageToShow).toBe("Terry");
routes.splice(2,0,{ 'area': "Billy" });
fixture.detectChanges();
expect(comp.PageToShow).toBe("Billy");
}));
Run Code Online (Sandbox Code Playgroud)
但是 …
jasmine angular2-routing angular2-testing angular2-observables angular
我目前正在使用AngularFire2处理Angular 2项目,我正在尝试将FirebaseListObservable转换为Promise.我知道它没有多大意义,因为Observables更有用,但是这个函数将成为链接多个promise的另一个函数的一部分.而且我不熟悉如何在一系列承诺中订阅Observable ...该函数在服务中执行,但它似乎没有返回任何东西.基本上,我想要做的是检查Firebase列表中是否已存在具有特定名称的对象并返回true或false.
constructor(private _af: AngularFire) { }
nameExists(name: string): Promise<boolean> {
return this._af.database.list('users')
.map(users => {
let exists = false;
users.forEach(user => {
if(user.name.toLowerCase() === name.toLowerCase()) {
console.log('Name already exists!');
exists = true;
}
});
return exists;
}).toPromise();
}
Run Code Online (Sandbox Code Playgroud)
constructor(private _usersService: UsersService) { }
check(name) {
this._usersService.nameExists(name)
.then(bool => console.log(bool));
}
Run Code Online (Sandbox Code Playgroud)
因此,当匹配时,函数会被执行并且在打印到控制台时似乎正常工作.但是,组件中的console.log()不会被执行.我想从未达到"那么"部分.另外,有没有办法在找到匹配后停止forEach循环?
任何帮助将不胜感激,因为我找不到任何答案.
我有一个计时器:
initiateTimer() {
if (this.timerSub)
this.destroyTimer();
let timer = TimerObservable.create(0, 1000);
this.timerSub = timer.subscribe(t => {
this.secondTicks = t
});
}
Run Code Online (Sandbox Code Playgroud)
如何在60分钟后向用户添加弹出窗口?我已经尝试过看几个问题(这个和这个),但它不是为了点击我.RxJS模式还是新手......
使用异步管道使用可观察数据服务直接在视图中更新数据,这证明难以测试(正常工作正常).
我希望能够更新视图,触发单击事件,然后测试模型是否已正确更新(由于单击),但在测试中,异步管道在其绑定的observable触发时不会呈现任何内容事件.所以我无法在测试中与DOM交互并测试交互的结果.
找不到任何人使用异步管道对组件进行单元测试的例子,所以我很茫然.任何反馈意见.
测试:
it('Updates the availability model correctly after UI interaction.', done => {
this.instance.morning$
.subscribe(data => {
let checkboxes = this.fixture.nativeElement.querySelectorAll('ion-checkbox');
TestUtils.trigger(checkboxes[0], 'click');
let morningModel = this.instance.model.morning;
expect(morningModel[0].v).toEqual(true);
done();
});
});
Run Code Online (Sandbox Code Playgroud)
模板:
<td *ngFor="let day of morning$ | async">
<ion-checkbox [(ngModel)]="day.v"></ion-checkbox>
</td>
Run Code Online (Sandbox Code Playgroud)
零件:
@Component({
templateUrl: 'build/modules/availability/availability.view.html',
selector: 'availability',
providers: [AvailabilitySvc],
directives: [Checkbox]
})
export class AvailabilityCom {
@Input() userId: string;
public morning$: any;
constructor(private svc: AvailabilitySvc) {
this.morning$ = svc.morning$;
this.setEvents();
}
ngOnInit(){
this.getAvailability();
}
getAvailability(){
return this.svc.get(this.userId); …Run Code Online (Sandbox Code Playgroud) unit-testing asynchronous ionic-framework angular2-observables angular
最近AngularFire如何处理对象/列表以及引用整个应用程序中的对象,我们遇到了一些严重的问题.
主要的是旧的AngularFireObject & AngularFireList工作与新的相比.我们的应用程序高度依赖于$key价值,因为我们非常规范化(如推荐).
现在,文档使用一个map示例来获取$key值,但是它的工作方式不一样,甚至valueChanges()看起来效果也不一样.
我不完全确定我们现在应该做些什么改变.
/* /items/
a/{name: 'Dennis', city: 'Dallas'}
b/{name: 'Katie', city: 'Austin'}
c/{name: 'Will', city: 'Chicago'}
*/
let myAfList = this.af.list('path/to/items');
let itemsFirst, itemsSecond, itemsThird;
myAfList.subscribe(items => itemsFirst = items);
setTimeout(_ => myAfList.subscribe(items => itemsSecond = items), 1000);
setTimeout(_ => myAfList.subscribe(items => itemsThird = items), 2000);
/* Results for all three item arrays
itemsFirst: [
{name: 'Dennis', city: 'Dallas', $key: 'a'},
{name: 'Katie', city: 'Austin', $key: …Run Code Online (Sandbox Code Playgroud) angular ×8
rxjs ×3
angularfire2 ×2
asynchronous ×2
angular6 ×1
angularjs ×1
firebase ×1
jasmine ×1
json ×1
memory-leaks ×1
observable ×1
setinterval ×1
timer ×1
typescript ×1
unit-testing ×1