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

时间:2019-04-18 12:37:58

标签: angular angular-httpclient angular-observable

我正在使用http服务从UserService获取用户数据。当我订阅可观察的内容时,这会造成内存泄漏。在开发人员控制台的“网络”标签中,可以看到发出了无限的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>

3 个答案:

答案 0 :(得分: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 :(得分: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 :(得分:1)

请勿在HTML上调用此类方法。

*ngIf="isLoggedIn()"

它将连续执行此方法。