2016-07-14 3 views
0

다음 코드 값 thisthen 함수 내에서 호출 할 때 null이됩니다. 여기 코드가 있습니다. 내가 뭔가 잘못하고 있거나 같은 또는 모든 작업이 있는가하면 주변이 문제를Promise 콜백에서이 값이 null이됩니다.

import { Injectable }  from '@angular/core'; 
import { Http, Response } from '@angular/http'; 
import { Headers, RequestOptions } from '@angular/http'; 

import { Observable }  from 'rxjs/Observable'; 
import { CanActivate, Router } from '@angular/router'; 

import { AuthService }   from '../services/auth.service'; 
import { WebAPISettings }   from '../services/webapisettings.service'; 

@Injectable() 
export class LoginService { 

    //_ngWEBAPISettings: WebAPISettings; 
    //_authService: AuthService; 

    constructor(private http: Http, private ngWEBAPISettings: WebAPISettings, private authService: AuthService) { 
    //this._ngWEBAPISettings = ngWEBAPISettings; 
    //this._authService = authService; 
    } 

    public login(username: string, password: string): Promise<any> { 

    let data = "grant_type=password&username=" + username + "&password=" + password; 
    let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }); 
    let options = new RequestOptions({ headers: headers }); 


    try { 
     debugger; 
     return this.http.post(this.ngWEBAPISettings.apiServiceBaseUri + "token", data, options) 
     .toPromise() 
     .then(function (res: Response) { 
      debugger; 
      let body = res.json(); 
      //let _authService: AuthService = new AuthService(); 

      this.authService.fillAuthDataFromLogin(body); 
      //this.router.navigate(['/Home']); 
      return body.data || {}; 
     }) 
     .catch(this.handleError); 

    } 
    catch (error) { 
     console.log(error); 

    } 

    } 


    private extractData() { 

    } 
    private handleError(error: any) { 
    debugger; 
    let errMsg = (error.message) ? error.message : 
     error.status ? `${error.status} - ${error.statusText}` : 'Server error'; 
    console.error(errMsg); // log to console instead 
    return Observable.throw(errMsg); 
    } 


} 

를 해결하고 난 여기에 크롬에서 디버깅하고하면 스크린 샷을 고정에서 저를 도와주세요입니다.

enter image description here

화살표 기능 똑같은 화면을 확인 사용 후 내가 Angular2 RC4를 사용하고 언급

enter image description here

한 가지

촬영.

return this.http.post(this.ngWEBAPISettings.apiServiceBaseUri + "token", data, options) 
    .toPromise() 
    .then((res: Response) => { // <----- 
     (...) 
    }); 

이 방법 thisLoginService 서비스의 인스턴스에 해당됩니다

+0

화살표 기능 : https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html 마지막 – basarat

답변

2

은이 어휘를 사용할 수 있도록 화살표 기능을 사용할 수 있습니다.

자세한 내용은이 문서를 참조하십시오 :

+0

확인 screenshot no nouck :( – rashfmnb

+2

dev 도구는 콘솔에 로그인하면 올바른 값을 얻을 수 있습니다. 이유 : Devtools는 ts 코드를 표시하지만 실제로는 javascript 코드 (es5)를 실행합니다. ,이 클래스의 인스턴스 대신 여전히 "null"입니다. – wzr1337

+0

아니요 너무 분명해! 나는 이유를 이해할 수 없다. ;-) –

관련 문제