繁体   English   中英

Angular2在组件中为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);
            });
        }

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

该服务以以下方式工作:

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

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函数不会创建自己的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(){} ,则可以组件的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)
);

第二个用例也应如此。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM