gpt4 book ai didi

Angular 2 - FormGroup ValueChanges退订

转载 作者:太空狗 更新时间:2023-10-29 17:06:37 28 4
gpt4 key购买 nike

我有一个带有 ValueChanges 事件的 FormGroup,当用户从组件的路由移动到另一个组件然后返回到该组件时,该事件不会从内存中释放。

这意味着如果用户导航离开组件然后返回组件 5 次,onFormChange 方法将触发 5 次,但其中只有 1 次是针对当前组件的。

我认为问题是我需要取消订阅 NgDestroy 事件中的 valueChanges 事件,但 valueChanges 事件没有可用的取消订阅方法。

我确定我必须取消订阅或释放某些内容的内存,但我不确定是什么。

import * as _ from 'lodash';
import {Observable} from 'rxjs/Rx';

import {Component, Input, Output, EventEmitter, OnInit, OnDestroy} from '@angular/core';
import {FormGroup} from '@angular/forms';

import {formConfig} from './toolbar.form-config';
import {JobToolbarVm} from '../view-model/job-toolbar.vm';
import {BroadcastService} from '../../../services/broadcast/broadcast.service';

@Component({
selector: 'wk-job-toolbar',
template: require('./toolbar.html'),
})
export class JobToolbarComponent implements OnInit, OnDestroy {

protected form: FormGroup;

@Input()
toolbar: JobToolbarVm;

@Output()
toolbarChanged = new EventEmitter<JobToolbarVm>();

@Output()
refresh = new EventEmitter<string>();

constructor(private broadcast: BroadcastService) {
}

ngOnInit() {

this.form = formConfig;
this.form.setValue(this.toolbar, {onlySelf: true});

// This ALWAYS RUNS when the form loads, ie. on the job route
console.log('FORM VALUE');
console.log(JSON.stringify(this.form.value, null, 2));

this.form.valueChanges
.debounceTime(2000)
.subscribe(
this.onFormChange.bind(this)
);
}

ngOnDestroy() {
//this.form.valueChanges.unsubscribe();
//this.onChanges.unsubscribe();
//this.toolbarChanged.unsubscribe();
//this.form = null;
}

onFormChange(data: any) {
// This runs whenever I go to a different route and then come back to this route
// There is also a memory leak, because this method fires multiple times based on how
// often I navigate away and come back to this route.
// e.g. Navigate away and then back 5 times, then I see this log statement 5 times
console.log('FORM VALUE2 - THIS KEEPS FIRING FOR EACH INSTANCE OF MY COMPOMENT');
console.log(JSON.stringify(this.form.value, null, 2));

JobToolbarVm.fromJsonIntoInstance(data, this.toolbar);

this.onChanges('data-changed');
}

onChanges($event: any) {
console.log('onChanges: ' + $event);
// console.log(this.toolbar);

// Send the toolbar object back out to the parent
this.toolbarChanged.emit(this.toolbar);

// Broadcast an event that will be listened to by the list component so that it knows when to refresh the list
this.broadcast.broadcast('job-admin-toolbar-changed', this.toolbar);
}
}

最佳答案

subscribe() 调用返回一个 Subscription,这就是您用来取消订阅的内容:

class JobToolbarComponent

private subscr:Subscription;

ngOnInit() {
...
this.subscr = this.form.valueChanges ...
...
}

ngOnDestroy() {
this.subscr.unsubscribe();
}
}

关于Angular 2 - FormGroup ValueChanges退订,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43840955/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com