Angular2取消订阅formGroup

时间:2017-01-20 09:06:50

标签: javascript angular typescript

我在表单上有取消订阅值更改的问题,我用它来进行验证。我想在精确的情况下关闭的方法:

this.taskForm.valueChanges.subscribe(data => {
                       ...
                this.output = data;
        });

我想在提交后删除此侦听器。我怎样才能做到这一点?我试过使用unsubscribe但它没有用。以下是我的尝试:

this.sub = this.taskCreate.valueChanges.subscribe(data => {
                          ...
                this.output = data;
        });

我试图添加this.sub.unsubscribe();,但它没有帮助。

onSubmit(form: FormGroup) {
    let context: number = 0;

    if(form.valid) {
        this.appService.addTask(form.value)
            .then(result => {
                this.lgModal.hide();
                this.taskCreate.reset({ priority: '' });
                this.cartBox.cart = [];
                this.cartBox.showCart = false;
                this.createTaskDone.emit();
                this.attachments.attachmentList = [];
                this.uploader.clearQueue();
                this.reloadContent.emit(context);   
                this.counter += 1;  
                console.log("COUNTER: ", this.counter);

            })} 
    else {
        this.formValidator(form);

    }

}

formValidator(form:FormGroup) {
    if(!form.controls['goal'].valid) this.formValid.goalErr = 1; else this.formValid.goalErr = 0;
    if(!form.controls['priority'].valid) this.formValid.priorityErr = 1; else this.formValid.priorityErr = 0;
    if(!form.controls['note'].valid) this.formValid.noteErr = 1; else this.formValid.noteErr = 0;

    this.taskCreate.valueChanges.subscribe(data => {
        this.formValidator(form);
        this.output = data;
    });
}

1 个答案:

答案 0 :(得分:3)

valueChanges内订阅formValidator似乎对我不利

formValidator(form:FormGroup) {
    if(!form.controls['goal'].valid) this.formValid.goalErr = 1; else this.formValid.goalErr = 0;
    if(!form.controls['priority'].valid) this.formValid.priorityErr = 1; else this.formValid.priorityErr = 0;
    if(!form.controls['note'].valid) this.formValid.noteErr = 1; else this.formValid.noteErr = 0;

    this.taskCreate.valueChanges.subscribe(data => {
        this.formValidator(form);
        this.output = data;
    });
}

我假设你真正想要的是移动

this.sub = this.taskCreate.valueChanges.subscribe(data => {
    this.formValidator(form);
    this.output = data;
});

在初始化this.taskCreate的代码下方,然后在onSubmit内进行this.sub.unsubscribe()调用。

我认为您的问题是this.taskCreate.valueChanges.subscribe(被多次调用,如果您使用this.sub = this.taskCreate.valueChanges.subscribe(,之前的订阅将被新的订阅覆盖,并且无法取消订阅,因为引用已丢失。