2016-10-22 6 views
3

현재 각도 js 2에서 로그인 인증과 관련하여 문제가 있습니다. 다음 코드에서는 비동기 문제와 마주하고 있습니다.각도 2 HTTP 서비스 동기화

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; 
} 
} 

currect 사용자 이름과 암호를 전달한 후이 코드를 실행할 때 여전히 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"; 
    } 

} 

} 
+0

라고 .. 서비스 파일입니까? 구성 요소 코드를 추가 할 수 있습니까? – Meir

+0

나는 코드를 업데이트했다. 제발 .. 통과 해. 고마워. – stackinfostack

+0

@stackinfostack는'loginAuthentication' 메소드를 디버그하고 거기에 오는 데이터 값을 볼 수 있나. – Pradeep

답변

1

입니다 비동기 문제. 당신이 만들고있는 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); 
    }); 
} 

다음 : -

나는 당신이 당신의 서비스에 관찰을 반환 할 것을 제안하고 구성 요소 클래스의 응답을 처리 할 여기에 최소한의 조정과 코드가 그에게 서비스 클래스를 fromt의 다음과 같이 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!") 
    ); 
} 

이제이 방법을 사용할 수 있습니다. 코드를 테스트하지 않았으므로 상자가 다 소모되지는 않았지만 요점은 분명합니다.

+0

귀하의 의견을 보내 주셔서 감사합니다. 이 코드는 오류없이 완벽하게 작동합니다. 고맙습니다. 나는 적절한 파일에 대한 대답으로 이것을 다시 넣을 것입니다. – stackinfostack

0

답변은 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; 
    } 


    } 
}