【问题标题】:Unsubscribe Angular valueChanges取消订阅 Angular valueChanges
【发布时间】:2023-01-04 20:03:52
【问题描述】:

我有一个服务类:

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
    }
}

createUserForm 方法在组件类中被调用。 是否需要取消上面代码中的'valueChanges'

【问题讨论】:

标签: angular typescript angular-reactive-forms


【解决方案1】:

我不明白在这种情况下什么时候会发生内存泄漏

例如:

@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()
}

如果“表单”对象被删除,订阅也将被删除

在下面的代码(https://angular-training-guide.rangle.io/routing/routeparams)中,我们应该取消订阅,因为注入的路由对象引用了组件对象。

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();
  }
}

【讨论】:

    猜你喜欢
    • 2017-05-12
    • 2019-05-25
    • 2021-07-22
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 2021-11-18
    相关资源
    最近更新 更多