简体   繁体   English

如何在angular 4中进行同步http调用

[英]How to make synchronous http calls in angular 4

I have an Angular 4 login Application.我有一个 Angular 4 登录应用程序。 I want login synchronous operation but asynchronous ?我要登录同步操作但异步? Can you help me?你能帮助我吗?

data.service.ts:数据.service.ts:

login(userName: string,pwd: string): Promise<User>  {
    const url =`loginLdap/${userName}&${pwd}`;  
    return this.http.get(url).toPromise()
    .then(response => response.json() as User)
    .catch(this.handleError);
}

user.service.ts :用户服务.ts:

public authenticate( userName: string, pwd: string): Observable<User>{
    this.dataService.login(email, password).then(items => this.items = items);
    console.log(this.items);

    if (this.items.success) {
        this._authenticated = true;
        ...
        return Observable.of(User);
    }else{ 
        return Observable.throw(new Error("System Error"));
    }

}

Please take a look at the Rxjs forkJoin operator.请查看 Rxjs forkJoin 运算符。 It will allow you to chain multiple Observables then take action after all of them have emit.它将允许您链接多个 Observable,然后在所有 Observable 都发出后采取行动。 Inside of the forjoin body add your if/else logic.在 forjoin 正文中添加您的 if/else 逻辑。 This would be an elegant way to accomplish what you are looking for.这将是一种优雅的方式来完成您正在寻找的东西。

If you have issues getting this setup, create a plunkr and we can work through it together.如果您在进行此设置时遇到问题,请创建一个 plunkr,我们可以一起解决。

If you don't have issues getting this working, please post the resulting file for others to view when you've gotten it working as desired.如果您在使用此功能时没有问题,请发布生成的文件供其他人查看,当您按需要运行时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM