在Promise回调中,值变为null

时间:2016-07-14 20:27:05

标签: javascript typescript angular

我使用以下代码值this变为null当我在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中调试它是截图请帮我修复它。

enter image description here

使用箭头功能后同样检查屏幕截图

enter image description here

有一点要提到我正在使用Angular2 RC4。

1 个答案:

答案 0 :(得分:3)

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

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

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

有关详细信息,请参阅此文档: