为什么代码段会造成内存泄漏?

问题描述 投票:0回答:3

我正在使用http服务从UserService获取用户数据。当我向observable订阅时,它会造成内存泄漏。在开发人员控制台的网络选项卡中,可以看到正在进行无限的http请求。

试图取消订阅ngOnDestroy()方法,但没有运气。

user.service.ts

getCurrentUserDetails(){
    return this.http.get<User>(`${this.config.apiUrl}/user/me`);
  }

navbar.component.ts

export class NavbarComponent implements OnInit, OnDestroy {

  user: User;
  userDetailsSubs: Subscription;
  constructor(
    private router: Router,
    private authenticationService: AuthenticationService,
    private userService: UserService
  ) { }

  ngOnInit() {
  }
  isLoggedIn() {
    const currentUser: User = this.authenticationService.currentUserValue;
    if (currentUser) {
      this.userDetailsSubs = this.userService.getCurrentUserDetails()
        .subscribe(
          data => {
            this.user = data;
          }
          , error => {
            console.log(error);
          });
      //this.userDetailsSubs.unsubscribe();
      return true;
    }
    else
      return false;
  }
  logout() {
    this.authenticationService.logout();
    this.router.navigate(['/login']);
  }
  ngOnDestroy() {
    this.userDetailsSubs.unsubscribe();
  }
}


navbar.component.html

<div class="sticky-top mb-3">
  <nav class="navbar navbar-expand-lg navbar-dark bg-danger justify-content-center p-3 mb-3" *ngIf="!isLoggedIn()">
    ..............
  </nav>
  <nav class="navbar navbar-expand navbar-dark bg-danger p-3 mb-5" *ngIf="isLoggedIn()">
      .
      .
      .
  </nav>
</div>

angular angular-httpclient angular-observable
3个回答
1
投票

您的isLoggedIn()函数是从变更检测模板触发的。将isLogged属性添加到组件并从ngOnInit设置它以避免多次调用。

isLogged: boolean;

ngOnInit() {
  const currentUser: User = this.authenticationService.currentUserValue;
    if (currentUser) {
      this.userDetailsSubs = this.userService.getCurrentUserDetails()
        .subscribe(
          data => {
            this.isLogged = true;
            this.user = data;
          }
          , error => {
            console.log(error);
          });
    }
    else
      this.isLogged = false;
}


2
投票

在你的班级创建一个属性,比如isLoggedInFlag

在您的isLoggedIn()方法下,在订阅下将其设置为true。

你有这样的看法:

<nav class="navbar navbar-expand-lg navbar-dark bg-danger justify-content-center p-3 mb-3" *ngIf="!isLoggedInFlag">

<nav class="navbar navbar-expand navbar-dark bg-danger p-3 mb-5" *ngIf="isLoggedInFlag">

1
投票

不要在HTML上调用这样的方法。

*ngIf="isLoggedIn()"

它将继续执行此方法。

© www.soinside.com 2019 - 2024. All rights reserved.