Angular 2同步Http服务

时间:2016-10-22 15:10:09

标签: angular

目前我在角度js 2中遇到有关登录验证的问题。    我在下面的代码中遇到了异步问题。

   import { Injectable } from '@angular/core';

   import { Http } from '@angular/http';
   import { UserData } from './UserData';
   import 'rxjs/add/operator/map'
   import 'rxjs/add/operator/toPromise'

   @Injectable()
   export class LoginserviceService {

   userData = new UserData('','');

   constructor(private http:Http) { }

  callService(username:string,passwrod:string):boolean {
    var flag : boolean;      
   (this.http.get('http://localhost:4200/data.json').
   map(response => response.json())).subscribe(
     data => this.userData = data ,
     error => alert(),
     () => {
       flag = this.loginAuthentication(username,passwrod);
    }           
  );     
  return flag;
 }

loginAuthentication(username:string,passwrod:string):boolean{
 if(username==this.userData.username && passwrod==this.userData.password){
   return true;
 }else{
   return false;
 }
 }

当我在传递当前用户名和密码后执行此代码时,它仍然返回false。

return flag

正在执行

 flag = this.loginAuthentication(username,passwrod);

最后我得到的结果是假的。

是否有任何解决方案如果我可以在角度2中使用同步方法或承诺。

以下是组件代码

import { Component, OnInit } from '@angular/core';
import { LoginserviceService } from '../loginservice.service';

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

constructor(private service : LoginserviceService) { 

 }

 ngOnInit() {

 }
 save() {

 var flag =  this.service.callService(this.model.userName,this.model.passWord);
  if(flag==true)
   {
    console.log("login Successfully done-----------------------------")
    this.model.success = "Login Successfully done";
   }

}

}  

2 个答案:

答案 0 :(得分:2)

我认为你的问题是正确的 - 它是同步/异步问题。你正在进行的http调用本质上是异步的,我认为你应该如何处理它们。

我建议您在服务中返回一个observable并处理组件类中的响应 - 这里是您的代码,只需对服务类进行最少的调整:

callService(username:string,passwrod:string):Observable<boolean> {
    var flag : boolean;      
    return (this.http.get('http://localhost:4200/data.json').
    map(response => response.json())).
    map(data => {
        this.userData = data;
        return this.loginAuthentication(username,passwrod);
    });
}

然后在您的组件类中,您现在可以像这样调用save方法:

save() {
    this.service.callService(this.model.userName,this.model.passWord).
    subscribe(
        success => {
            if(success) {
                console.log("login Successfully done-----------------------------");
                this.model.success = "Login Successfully done";
            },
        error => console.log("login did not work!")
    );
}

现在应该可以了。我没有测试代码,所以它可能没有开箱即用,但我希望这一点很明确。

答案 1 :(得分:1)

请详细说明esef给出的答案 下面是组件和服务文件。并且代码工作正常。

import { Component, OnInit } from '@angular/core';
import { LoginserviceService } from '../loginservice.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  model:any={};
  constructor(private service : LoginserviceService) { 
}

ngOnInit() {

}
save() {
   this.service.callService(this.model.userName,this.model.passWord).
   subscribe(
      success => {
        if(success) {
            console.log("login Successfully done----------------------------    -");
            this.model.success = "Login Successfully done";
     }},
    error => console.log("login did not work!")
  );
 }

}

以下是服务档案..

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { UserData } from './UserData';
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/toPromise'
import {Observable} from 'rxjs/Rx'

@Injectable()
   export class LoginserviceService {
   userData = new UserData('','');   
   constructor(private http:Http) { }

    callService(username:string,passwrod:string):Observable<boolean> {
     var flag : boolean;      
     return (this.http.get('http://localhost:4200/data.json').
       map(response => response.json())).
        map(data => {
          this.userData = data;
          return this.loginAuthentication(username,passwrod);
        });
      }

  loginAuthentication(username:string,passwrod:string):boolean{
     if(username==this.userData.username && passwrod==this.userData.password){
        console.log("Authentication successfully")
        return true;
   }else{
     return false;
   }


  }
}