angular - 没有 ngOnDestroy,Angular 代码无法工作
问题描述
我有一个用于登录系统的组件,如下所示:
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class LoginComponent extends OtherLoginComponent implements OnInit{
loginWithPass = !(<RandomService>this.randomService).variable1;
lText = !(<RandomService>this.randomService).variable1 ? 'LOG IN' : 'LOG IN 123';
ngOnInit() {
if(location.href.startsWith(environment.variable_url)){
(<RandomService>this.randomService)._variable2 = true;
this.lText = 'LOG IN 123';
}
this.loginWithCredentials = !(<RandomService>this.randomService).variable1;
}
ngOnDestroy() {
}
userPass() {
this.loginWithPass = true;
(<RandomService>this.randomService)._variable2 = false;
this.lText = 'LOG IN';
}
}
以上所有方法都有效,但是当我删除空的 ngOnDestroy() 时,出现以下错误:
Uncaught (in promise): TypeError: Cannot read property 'unsubscribe' of undefined
有谁知道为什么会这样?我应该在我的 ngOnDestroy 中包含什么,所以它不是空的?
解决方案
这可能是因为您忘记在实现 OnInit 之后添加 OnDestroy ... Angular 使用反射并在调用它之前查看您是否已实现 OnDestroy。通常你在 NgOndestroy 中加入 unsubscribe 调用,你清理不再需要的视图数据。
推荐阅读
- javascript - 使用 MongoJs 找不到记录
- c# - 如何使用 Visual Studio 设置 Windows 窗体应用程序的默认文本输入状态?
- r - Python相当于dplyr的summary
- javascript - 用 promise 监听 firestore 快照的变化
- r - 将数据从 yyyyMM 转换为 yyyyQQ
- python - 想知道如何将第一个字母大写,如果不大写会出错
- java - 以下设计模式如何成为工厂方法。我相信它更像是一个抽象工厂而不是工厂方法
- c++ - 文本出现多次
- c++ - '&&' 运算符的这种用法在 C++ 中意味着什么?
- python - 访问也是字典的 JSON doc 中的字典值,并将内部 dict 转换为字符串