我正在使用以下代码值,当在this函数内部调用它时,then变为空,这是代码。我是在做错事还是类似的事情,或者有任何解决此问题的方法

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


}


我正在Chrome中调试它,这里是屏幕截图,请帮助我修复它。

javascript - 在Promise回调中此值变为空-LMLPHP

使用箭头功能后,请检查屏幕快照

javascript - 在Promise回调中此值变为空-LMLPHP

提及一件事,我正在使用Angular2 RC4。

最佳答案

您可以使用箭头功能来使用词汇:

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


这样,this将对应于LoginService服务的实例。

有关更多详细信息,请参见此文档:


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

关于javascript - 在Promise回调中此值变为空,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38383693/

10-11 05:33