Angular2在组件中为null

时间:2017-01-15 21:57:45

标签: javascript angular typescript angular2-services angular-promise

我期待一些奇怪的情况,其中“this”在组件内部为空。 到目前为止,我在两种情况下看到了它:

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被调用时,这是空的。

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

1 个答案:

答案 0 :(得分:5)

使用() => {}(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)
);

同样适用于您的第二个用例。