다음 코드 값 this
은 then
함수 내에서 호출 할 때 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);
}
}
를 해결하고 난 여기에 크롬에서 디버깅하고하면 스크린 샷을 고정에서 저를 도와주세요입니다.
화살표 기능 똑같은 화면을 확인 사용 후 내가 Angular2 RC4를 사용하고 언급한 가지
촬영.return this.http.post(this.ngWEBAPISettings.apiServiceBaseUri + "token", data, options)
.toPromise()
.then((res: Response) => { // <-----
(...)
});
이 방법 this
가 LoginService
서비스의 인스턴스에 해당됩니다
화살표 기능 : https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html 마지막 – basarat