Angular2在组件中为null [英] Angular2 this is null in component

查看:169
本文介绍了Angular2在组件中为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期望组件中"this"为null的一些怪异情况. 到目前为止,我在两种情况下看到了它:

I'm expecting some weird situations where "this" is null inside a component. SO far, I saw it in two situations:

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

在函数(错误)中,该值为null,因此我无法分配相应的错误.

In the function(error) this is null so I cannot assign the corresponding error.

该服务以下列方式工作:

The service is working in the following way:

  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时,此值将丢失.

So the this value is lost when the service handleError is called.

2)-使用Sweetalert

2) - Using 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.

Here when I confirm and I try to execute the clearSession is called, this is null.

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

I don't know if they are two different issues or if both are cause by the same issue.

推荐答案

使用() => {}(ES6箭头功能)作为回调,以便this引用该组件,如

Use () => {} (ES6 arrow function) as a callback in order for this to refer to the component, as the arrow function does not create its own this context:

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(){},则可以

Still, if you want to use function(){}, you can bind component's this context to the callback function as following:

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

第二个用例也应如此.

这篇关于Angular2在组件中为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆