在Angular2中,如何在填充其他对象属性之前不调用方法
使用Angular2,我试图在填充“itemU”的属性之前不调用setGroups()方法。属性由名为setMyData()的方法中的api调用填充 填充这些属性后,如何调用此.setGroups()?在Angular2中,如何在填充其他对象属性之前不调用方法,angular,Angular,使用Angular2,我试图在填充“itemU”的属性之前不调用setGroups()方法。属性由名为setMyData()的方法中的api调用填充 填充这些属性后,如何调用此.setGroups()? //inside of ngOnInit() this.myService.getMyData(this.userId) .takeUntil(this.ngUnsubscribe) .subscribe(user => this.s
//inside of ngOnInit()
this.myService.getMyData(this.userId)
.takeUntil(this.ngUnsubscribe)
.subscribe(user => this.setMyData(user));
if(this.itemU.gr1 || this.itemU.gr2 || this.itemU.gr3){
this.setGroups();
}
//properties are getting set after the break point passes the if(this.itemU.gr1..
setMyData通过api调用填充this.itemU.gr1 | | this.itemU.gr2 | | this.itemU.gr1属性
//outside of ngOnInit()
setMyData(user: models.ListOfResponse) {
this.itemU = objectSample[0];
//sets gr1
this.myService.get1(this.u.id )
.subscribe(access => this.setA(access));
//sets gr2
this.myService.get2(this.u.key, true)
.subscribe(
groups => this.hasPerms(groups, false)
,error => this.isUnavailable = true
);
//set gr3
this.myService.get2(this.u.key, true)
.subscribe(
groups => this.hasPerms(groups, true)
,error => this.isUnavailable = false
);
}
下面是“hasPerms()”方法的示例:
我会在get2和3上执行Observable.forkJoin,然后执行setGroups()。不过,这个.setA似乎必须在之前执行。这就是为什么forkJoin在get1中
setMyData(user: models.ListOfResponse) {
this.itemU = objectSample[0];
//sets gr1
this.myService.get1(this.u.id )
.subscribe(access => {
this.setA(access)
Rx.Observable.forkJoin(
this.myService.get2(this.u.key, true),
this.myService.get2(this.u.key, true)
)
.subscribe(
groups => {
// here groups is an array so execute this.hasPerms(groups, false) in a loop
// then call this.setGroups(); as everything is completed now
}
,error => this.isUnavailable = true
);
});
}您也可以使用rxjs的行为主体:
itemUPopulated$ = new BehaviorSubject(false);
this.myService.getMyData(this.userId)
.takeUntil(this.ngUnsubscribe)
.subscribe(user => this.setMyData(user));
itemUPopulated$.subscribe(populated => {
if (populated) {
this.setGroups();
}
});
现在,在代码的后面,每当填充itemU时,只要执行
itemUPopulated$.next(true);
可能在hasPerms1()函数中:
hasPerms1(groups: models.Stuff[], isTrue: boolean) {
if (isTrue) {
this.itemU.gr2 = groups;
itemUPopulated$.next(true);
}
else {
this.itemU.gr3 = "";
}
}
hasPerms1(groups: models.Stuff[], isTrue: boolean) {
if (isTrue) {
this.itemU.gr2 = groups;
itemUPopulated$.next(true);
}
else {
this.itemU.gr3 = "";
}
}