javascript - 在 Promise 回调中,此值变为 null

标签 javascript typescript angular

当我在 then 函数中调用它时,我正在使用以下 this 的代码值变为 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);
  }


}

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

enter image description here

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

enter image description here

有一件事要提一下,我使用的是 Angular2 RC4。

最佳答案

您可以使用箭头函数来使用词法 this:

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

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

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

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

相关文章:

javascript - Array.slice 和 Array().slice 之间的区别

javascript - Typescript 递归映射对象属性类型 : object and array element types

javascript - Angular 2 - 获取表单控件验证器

javascript - 函数上的 Angular 2 异步管道

javascript - 使用 lodash 组合具有相同键的对象

javascript - Array.fill 和创建数组的 for 循环有什么区别

用于调整 Blogger 帖子中照片大小的 JavaScript

javascript - 将 key 对添加到 typescript 中的对象数组

javascript - 为什么 Typescript lambda 函数会被大括号破坏?

angular - 订阅子组件的Observable(valueChanges)