Angular 角2同步负载

Angular 角2同步负载,angular,typescript,httprequest,Angular,Typescript,Httprequest,我的区域设置或会话存储中有一个JWT令牌,它保存用户ID 因此,如果用户在以下路径上刷新 test.com/route2 app.components.ts通过http请求获取角色 constructor( private userService: UserService ) { this.userService.getUser(this.subId()).toPromise().then((data)=>{ this.setLoggedUser

我的区域设置或会话存储中有一个JWT令牌,它保存用户ID

因此,如果用户在以下路径上刷新

test.com/route2

app.components.ts通过http请求获取角色

    constructor(
    private userService: UserService
   )
  {
    this.userService.getUser(this.subId()).toPromise().then((data)=>{      this.setLoggedUser(data);
});
  }
所以现在问题出在Route2的ngInit事件上,它是Route2.component.ts. 我正在做一个获取客户的http请求,但问题是它是在设置LoggedUser之前触发的,它抛出null错误

   this.groupService.getAllCustomersOfGroup(this.getLoggedUser().Group.Id).subscribe(
  data => this.customers = data,
  err => this.error(err),
  () => { this.loadingHideSucces(); }
);

您必须链接调用以按正确的顺序获取数据,例如,您可以实现
getLoggedUser()
方法来返回一个
可观察的

ngOninit() {
  this.getLoggedInUser().switchMap(user=>{
    this.groupService.getAllCustomersOfGroup(user.Group.Id).subscribe(
        data => this.customers = data,
        err => this.error(err),
        () => {
            this.loadingHideSucces();
        }
    );
  })
}

getLoggedInUser():Observable<LoggedInUser>{
 // logic to fetch user data, returns an observable.
}
ngOninit(){
this.getLoggedInUser().switchMap(用户=>{
this.groupService.getAllCustomersOfGroup(user.Group.Id).subscribe(
data=>this.customers=data,
err=>this.error(err),
() => {
this.loadinghidesuccess();
}
);
})
}
getLoggedInUser():可观察{
//获取用户数据的逻辑,返回一个可观察值。
}

由于您的组件名为“route2”,我猜它用于
ng路由器出口
标记,然后您也可以使用。

没有同步请求。您只需要通过返回其他人可以订阅的可观察的异步调用来正确地链接异步调用。有几个教程展示了如何使用带有Angular()的observables和topromise、await和async(ES2016?)的observables,但在构造函数idk中没有说明为什么
await
async
不进行任何同步。它仍然是异步的。这只是更方便的语法。