相关疑难解决方法(0)

Angular 2 - 关闭窗口时执行代码

我正在使用角度2进行聊天应用程序.

当用户关闭窗口时,如何将完成聊天命令发送到后端?

我的组件有一个方法,调用后端服务以下面的方式结束聊天

 endChat() {
        this.chatService.endChat(this.chatSessionInfo).subscribe(
            result => this.OnGetMessages(result),
            error => this.OnChatEndError(error)
        );
    }
Run Code Online (Sandbox Code Playgroud)

关闭窗口时如何执行该代码?如何检测窗口关闭事件?

我尝试使用ngOnDestroy但由于某种原因代码没有被执行.

在我的Component.ts中我有.

import { Component, OnInit, AfterViewChecked, ElementRef, ViewChild,OnDestroy} from '@angular/core';

export class ChatComponent implements OnInit, AfterViewChecked,OnDestroy  {
Run Code Online (Sandbox Code Playgroud)

最后

 ngOnDestroy() { 
    this.endChat();
 }
Run Code Online (Sandbox Code Playgroud)

谢谢!

typescript angular

28
推荐指数
2
解决办法
4万
查看次数

angular2:CanDeactivate guard

我创建了一个CanDeactivate防护,它返回一个observable,它应用于一个加载在内部嵌套路由器插座中的组件.每当有人试图导航到另一个URL时,是否应该调用此警卫?我问这个是因为我的情况并没有发生这种情况.

在我的情况下,警卫只会被调用第一个"不同"的URL.让我试着用一个例子来解释它.假设我总是返回false并且我试图从同一个组件导航到不同的url:

/A --> guard called
/B --> guard called
/B --> no navigation and no guard called
/A --> guard called
/A -->guard not called and no navigation
Run Code Online (Sandbox Code Playgroud)

这是预期的行为吗?

编辑好吧,它似乎是.刚刚建立了一个包含3个组件的小样本,只有在用户第一次尝试导航到特定网址时才会调用防护...这真的很奇怪......

无论如何,这是我正在使用的代码:

// app.routing
import {NgModule} from "@angular/core";
import {Routes, RouterModule, Route, CanDeactivate, ActivatedRouteSnapshot, 
        RouterStateSnapshot} from "@angular/router";
import { MainComponent } from "./main/main.component";
import { OtherComponent } from "./other/other.component";
import { Other3Component } from "./other3/other3.component";
import {Observable} from "rxjs/observable";
const fallback: Route = {
    path: "**",
    redirectTo: "/main",
    pathMatch: …
Run Code Online (Sandbox Code Playgroud)

angular2-routing angular2-guards angular

14
推荐指数
2
解决办法
1万
查看次数

如果从 ngOnDestroy 生命周期钩子中调用异步函数,组件垃圾如何收集?

我有一个角度组件,在 ngOnDestroy 钩子内部,我想添加异步函数,使 http 调用可以删除某些内容。我想知道内存是如何管理的以及回调函数的范围是什么?如果垃圾收集器决定通过引用释放内存是否意味着该组件将保留在内存中直到删除回调完成?这是stackblitz 演示和我正在测试的示例。

第一的:

 ngOnDestroy() {
    this.http.delete(...)
  }
Run Code Online (Sandbox Code Playgroud)

由于我没有提供 .then(...) 回调,这是否意味着组件可以从内存中完全卸载?

第二:

 async ngOnDestroy() {
    await this.http.delete(...)
  }
Run Code Online (Sandbox Code Playgroud)

为什么组件会被销毁并且不等待 delete() 完成?

第三:

 ngOnDestroy() {
    this.http.delete(...).then(console.log);
  }
Run Code Online (Sandbox Code Playgroud)

由于我提供了回调函数,这是否意味着组件将保留在内存中直到回调函数完成?

我怎样才能看到内存分配中发生了什么?有没有办法查看垃圾收集器的作用,或者在从内存中释放某个对象时指定回调函数?谢谢

编辑

根据这篇内存管理 MDN 文章,自 2012 年以来,引用计数算法已被标记和清除所取代,如果我使用 --expose-gc 标志运行我的 ng 服务节点进程,我可以暴露垃圾收集器

javascript async-await angular

6
推荐指数
0
解决办法
1632
查看次数