ViewDestroyedError:尝试使用被破坏的视图:Angular 4 中的detectChanges [英] ViewDestroyedError: Attempt to use a destroyed view: detectChanges in Angular 4

查看:21
本文介绍了ViewDestroyedError:尝试使用被破坏的视图:Angular 4 中的detectChanges的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Angular 4 的新手并试图构建一个简单的路由,但是当我尝试使用 this.router.navigate(['./admin/login']); 在成功注册时重定向时; 所以它抛出这个错误 ViewDestroyedError: Attempt to use a destroyed view:detectChanges in console.log.这是我的 register.component.ts 文件的样子:

import { Component, OnDestroy } from '@angular/core';从@angular/router"导入{路由器};从@angular/core"导入{ChangeDetectionStrategy};import { FormValidationService } from "../../validations/form-validation.service";从'angular2-flash-messages'导入{ FlashMessagesService};从 '../../services/auth.service' 导入 { AuthService };@成分({templateUrl: 'register.component.html',changeDetection: ChangeDetectionStrategy.OnPush})导出类 RegisterComponent 实现 OnDestroy {名称:字符串;电子邮件:字符串;密码:字符串;re_password:字符串;手机:字符串;构造函数(私有表单验证:FormValidationService,私人闪存:FlashMessagesService,私人身份验证:AuthService,私有路由器:路由器) { }注册用户(){变量用户 = {名称:this.name,电子邮件:this.email,密码:this.password,re_password: this.re_password,手机:this.mobile,}if(!this.formValidation.validateEmail(this.email)){this.flash.show("电子邮件格式无效!",{ cssClass: 'alert-danger', timeout: 3000 });返回假;}this.auth.authRegisterUser(user).subscribe(data => {如果(数据.成功){this.flash.show("用户创建成功!", { cssClass: 'alert-success', timeout: 3000 });this.router.navigate(['./admin/login']);//<-------这是问题-------------->}别的{this.flash.show(data.message, { cssClass: 'alert-success', timeout: 3000 });返回假;}});}}

并且我创建了一个 auth.module.ts 文件,其中我提到了这两个的路由.

import { NgModule } from '@angular/core';从'@angular/forms'导入{FormsModule};从'angular2-flash-messages'导入{ FlashMessagesModule };import { LoginComponent } from './login.component';从'./register.component'导入{注册组件};从 '../../services/auth.service' 导入 { AuthService };从'./auth-routing.module'导入{AuthRoutingModule};@NgModule({进口:[ AuthRoutingModule, FormsModule, FlashMessagesModule ],声明: [登录组件,注册组件],提供者:[AuthService],})导出类 AuthModule { }

我还有这个路由文件 auth-routing.module.ts 在这里你可以查看文件:

import { NgModule } from '@angular/core';从'@angular/router' 导入 { Routes, RouterModule };import { LoginComponent } from './login.component';从'./register.component'导入{注册组件};const 路由:路由 = [{小路: '',数据: {title: '示例页面'},孩子们: [{路径:'登录',组件:登录组件,数据: {title: '登录页面'}},{路径:'注册',组件:注册组件,数据: {title: '注册页面'}}]}];@NgModule({进口:[RouterModule.forChild(routes)],出口:[路由器模块]})导出类 AuthRoutingModule {}

现在问题出在哪里没有得到它.它在此处显示此控制台是问题的屏幕截图.

任何建议都会有所帮助.谢谢!(提前)

解决方案

问题实际上不在于重新路由,而在于闪现消息.在您的 RegisterComponent 的 html 中,您有 ;用户注册后,您1.调用闪信,2.重新路由到登录页面.

this.flash.show("用户创建成功!", { cssClass: 'alert-success', timeout: 3000 });this.router.navigate(['./admin/login']);

问题是 flash-messages 被告知在 RegisterComponent.html 文件中显示,该文件被重新路由破坏,因此导致 flash-messages 试图在被破坏的Register"视图中显示其消息.

我目前不知道有什么办法可以解决这个问题.似乎一个应用程序只能在一个永久位置显示闪消息.您可以使用的一种解决方案是将您的 flash-message 选择器放在 app.component 中的某个位置.另一种解决方案是从 RegisterComponent 发出一个通知,该通知会被您希望在其中显示消息的视图组件接收到,然后模拟"带有样式类似于 flash-message 和超时的 div 的 flash-message.

i am new to Angular 4 and trying to build a simple routing but when i am trying to redirect on successful register using this.router.navigate(['./admin/login']); so its throwing this error ViewDestroyedError: Attempt to use a destroyed view: detectChanges in console.log. Here is how my register.component.ts file looks like:

import { Component, OnDestroy } from '@angular/core';
import { Router } from "@angular/router";
import { ChangeDetectionStrategy } from '@angular/core';

import { FormValidationService } from "../../validations/form-validation.service";
import { FlashMessagesService } from 'angular2-flash-messages';
import { AuthService } from '../../services/auth.service';

@Component({
  templateUrl: 'register.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class RegisterComponent implements OnDestroy  {
  name: String;
  email: String;
  password: String;
  re_password: String;
  mobile:String;


  constructor(private formValidation: FormValidationService, 
            private flash: FlashMessagesService, 
            private auth: AuthService,
            private router: Router) { }




  registerUser(){   
    var user = {
        name: this.name,
        email: this.email,
        password: this.password,
        re_password: this.re_password,
        mobile:this.mobile,
    }



    if(!this.formValidation.validateEmail(this.email)){
        this.flash.show("Invalid email format!",{ cssClass: 'alert-danger', timeout: 3000 });
        return false;
    }

    this.auth.authRegisterUser(user).subscribe(data => {
      if(data.success){
        this.flash.show("User created successfully!", { cssClass: 'alert-success', timeout: 3000 });
        this.router.navigate(['./admin/login']);     // <-------This is the problem -------------->
      }else{
        this.flash.show(data.message, { cssClass: 'alert-success', timeout: 3000 });
        return false;
      }
    });

  }

}

And i have created a auth.module.ts file in which i have mentioned the route for these two.

import { NgModule } from '@angular/core';
import { FormsModule }   from '@angular/forms';
import { FlashMessagesModule } from 'angular2-flash-messages';

import { LoginComponent } from './login.component';
import { RegisterComponent } from './register.component';
import { AuthService } from '../../services/auth.service';


import { AuthRoutingModule } from './auth-routing.module';

@NgModule({
  imports: [ AuthRoutingModule, FormsModule, FlashMessagesModule ],
  declarations: [
    LoginComponent,
    RegisterComponent
  ],
  providers: [AuthService],
})
export class AuthModule { }

Also i have this routing file auth-routing.module.ts here you can view the file:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { LoginComponent } from './login.component';
import { RegisterComponent } from './register.component';

const routes: Routes = [
  {
    path: '',
    data: {
      title: 'Example Pages'
    },
    children: [
      {
        path: 'login',
        component: LoginComponent,
        data: {
          title: 'Login Page'
        }
      },
      {
        path: 'register',
        component: RegisterComponent,
        data: {
          title: 'Register Page'
        }
      }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AuthRoutingModule {}

Now where is the problem not getting it. Its showing this Console here is the screenshot of the problem.

Any suggestion will be helpful. Thank you! (in advance)

解决方案

The problem is actually not the rerouting, but with flash-messages. In your RegisterComponent's html, you have the <flash-messages></flash-messages>; after the user is registered, you 1. call flash-messages, 2. reroute to login page.

this.flash.show("User created successfully!", { cssClass: 'alert-success', timeout: 3000 });
this.router.navigate(['./admin/login']);

The problem is that flash-messages is being told to display in the RegisterComponent.html file, which is destroyed by the reroute, so that results in flash-messages trying to display its message in the destroyed 'Register' view.

I currently don't know of any way around this. It appears that an app can only have flash-messages in one permanent location. One solution you could use is to put your flash-messages selector somewhere in app.component. Another solution would be to emit a notification from RegisterComponent that gets picked up by the view component you wish to display a message in, and sort of 'mock' a flash-message with a div styled like flash-message and a timeout.

这篇关于ViewDestroyedError:尝试使用被破坏的视图:Angular 4 中的detectChanges的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆