简体   繁体   English

等待HTTP请求在angular 4服务中完成

[英]Wait for http request to complete in angular 4 service

This might be a basic question. 这可能是一个基本问题。 but I am new to angular services(promises,observable etc). 但是我是角度服务(承诺,可观察的等等)的新手。

basically, I have a button(login) in login page , once user clicks on that button I want to validate and generate token. 基本上,我在登录页面上有一个按钮(登录),一旦用户单击该按钮,我就想验证并生成令牌。 once the token is assigned field on service, then I will redirect to some page(Home page). 一旦在服务上分配了令牌,那么我将重定向到某个页面(主页)。 But what is happening now is, when I made a function call to angular service function, before it gets(asynchronously) the token itself my page is redirecting. 但是现在发生的是,当我对角度服务函数进行函数调用时,在它获得(异步)令牌本身之前,我的页面正在重定向。


app-data-service 应用数据服务

`

    import { Injectable } from '@angular/core';
    import { HttpClient,HttpHeaders } from '@angular/common/http';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/mergeMap';
    import 'rxjs/add/operator/toPromise';
    @Injectable()
    export class AppDataServiceService {
      tokenGenerated:any='';
      constructor(private http: HttpClient) { 

      }

      getData(){
        console.log("Started.. in service");
         this.http.get('http://host/url').toPromise()
         .then(this.extractData);

      }
      private extractData(res: Response) {
        console.log("completed.. in service");
        this.tokenGenerated=res;
        return res;
    }

    }
    `---------------------------------------------------
    login component

    import { Component, OnInit } from '@angular/core';
    import { AppDataServiceService } from '../app-data-service.service';
    import { Router } from '@angular/router';

    @Component({
      selector: 'app-login-component',
      templateUrl: './login-component.component.html',
      styleUrls: ['./login-component.component.css']
    })
    export class LoginComponentComponent implements OnInit {

      constructor(private dataService:AppDataServiceService,private router:Router) {

       }

      ngOnInit() {
      }

      submit(){
        this.dataService.getData();
        console.log('after executing service');
        this.router.navigate(['/view']);
      };

    }
-------------------------------------------------------------
   login html

<div class="container">
  <label><b>Username</b></label>
  <input type="text" placeholder="Enter Username" name="uname" >

  <label><b>Password</b></label>
  <input type="password" placeholder="Enter Password" name="psw" >



</div>

<input type="button" (click)='submit()'  value="Login"  name="submit"/>

console output in browser: 浏览器中的控制台输出:

Started.. in service 在服务中开始

after executing service 执行服务后

completed.. in service 服务完工..

Can you help me to let http call wait till its completion. 您能帮我让http调用等到它完成吗? I am not sure if that is the way to use promise to make the call synchronous. 我不确定这是否是使用promise来使呼叫同步的方法。

You should return a promise (or Observable) from your service, and subscribe to that in the component. 您应该从服务中返回一个Promise(或Observable),并在组件中进行订阅。

Without doing so, the component has no way of knowing when your asynchronous code has finished executing, so it prints that log statement immediately 如果不这样做,该组件将无法知道您的异步代码何时完成执行,因此它将立即打印该日志语句

Change the service like so: 像这样更改服务:

getData(){
    console.log("Started.. in service");
    return this.http.get('http://host/url').toPromise()
        .then(res => this.extractData(res));
}

Then in the component 然后在组件中

submit(){
    this.dataService.getData().then(() => {
        console.log('after executing service');
        this.router.navigate(['/view']);
    };
};

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

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