首页 > 解决方案 > 没有 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 中包含什么,所以它不是空的?

标签: angular

解决方案


这可能是因为您忘记在实现 OnInit 之后添加 OnDestroy ... Angular 使用反射并在调用它之前查看您是否已实现 OnDestroy。通常你在 NgOndestroy 中加入 unsubscribe 调用,你清理不再需要的视图数据。


推荐阅读