Angular2 this 在组件中为 null

Angular2 this is null in component

我期待一些奇怪的情况,其中 "this" 在组件内为 null。 到目前为止,我看到了两种情况:

1)当承诺被拒绝时:

if (this.valForm.valid) {
            this.userService.login(value).then(result => {
                if(result.success){
                    this.toasterService.pop("success", "Exito", "Inicio de session correcto");
                    this.sessionService.setUser(result.data);
                    this.router.navigateByUrl('home');
                }
                else{
                    this.error = result.code;
                }
            },function(error){
                console.log("ERROR: " + error);
                this.error = "ERROR__SERVER_NOT_WORKING";
                console.log(this.error);
            });
        }

在函数(error)中,this为空,所以我无法分配相应的错误。

该服务按以下方式工作:

  login(login : Login) : Promise<Response> {
      return this.http
      .post(this.serverService.getURL()  + '/user/login', JSON.stringify(login), {headers: this.headers})
      .toPromise()
      .then(res => res.json())
      .catch(this.handleError);
  }

    private handleError(error: any): Promise<any> {
      console.log('An error occurred', error); // for demo purposes only
      return Promise.reject(error.message || error);
    }

因此调用服务 handleError 时 this 值丢失。

2) - 使用 sweetalert

logout(){
        swal({
            title: 'Are you sure?',
            text: "You won't be able to revert this!",
            type: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
            }).then(function() {
                this.sessionService.clearSession();
                this.router.navigateByUrl('login');
        }, function(){
            //Cancel
        });
    }

这里当我确认并尝试执行 clearSession 被调用时,这是 null。

我不知道它们是两个不同的问题还是由同一个问题引起。

使用 () => {}(ES6 箭头函数)作为回调,以便 this 引用组件,因为 arrow function 不会创建自己的 this上下文:

this.userService.login(value).then(
    (result) => {
        this.toasterService.pop("success", "Exito", "Login successful!");
    }, 
    (error) => {
        // now 'this' refers to the component class
        this.error = "SERVER_ERROR";
    }
);

不过,如果您想使用 function(){},您可以 bind 组件的 this 上下文到回调函数,如下所示:

this.userService.login(value).then(
    function(result) {
        this.toasterService.pop("success", "Exito", "Login successful!");
    }.bind(this), 

    function(error) {
        // now 'this' refers to the component class
        this.error = "SERVER_ERROR";
    }.bind(this)
);

您的第二个用例也应如此。