[英]Unsubscribe Angular valueChanges
我有一个服务 class:
class UserFormService {
createUserForm() {
const userForm = new FormGroup({
firstName: new FormControl(),
lastName: new FormControl(),
displayName: new FormControl()
})
userForm.controls.firstName.valueChanges.subscribe(firstName => {
if(!userForm.value.displayName) {
userForm.controls.displayName.setValue(`${firstName} additional text`)
}
})
return userForm
}
}
class组件中调用了createUserForm方法,是否需要取消上面代码中的'valueChanges'
我无法理解在这种情况下何时会发生 memory 泄漏
例如:
@Component({
selector: 'app-user-test',
standalone: true,
imports: [CommonModule, ReactiveFormsModule],
templateUrl: './user-test.component.html',
styleUrls: ['./user-test.component.css']
})
export class UserTestComponent {
constructor(private userFormService: UserFormService) { }
form = this.userFormService.createUserForm()
}
如果'表格'object被删除,订阅也将被删除
在下面的代码 ( https://angular-training-guide.rangle.io/routing/routeparams ) 中,我们应该取消订阅,因为注入的路由 object 引用了组件 object。
export class LoanDetailsPage implements OnInit, OnDestroy {
id: number;
private sub: any;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.id = +params['id']; // (+) converts string 'id' to a number
// In a real app: dispatch action to load the details here.
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.