Что я должен уничтожить на угловой?Как я должен? - PullRequest
0 голосов
/ 21 января 2019

Я посмотрел на угловую документацию, другие ресурсы, но ничего не нашел. Я работаю на Angular7. Как я могу сделать процесс уничтожения?

Ответы [ 3 ]

0 голосов
/ 21 января 2019
See this scenario


import { Subscription } from 'rxjs';
  currentUserSub: Subscription;


  getCurrentUser() {
    this.currentUserSub = this.authenticationService.currentUser.subscribe(x => {
      if (x) {
        this.currentUser = x[0].MemberId;
      } else { }
    });



 ngOnDestroy() {
    // unsubscribe to ensure no memory leaks
    this.currentUserSub.unsubscribe();
  }


  }
0 голосов
/ 21 января 2019

Чистый способ отписаться от всех наблюдаемых в компоненте:

//declare 
private ngUnsubscribe: Subject<any> = new Subject<any>();


//add takeUntill where subscribing to observables 
this.myService.serviceFunction()
                .pipe(takeUntil(this.ngUnsubscribe))
                .subscribe(
                    res => {
                        // use res
                    },
                    err => {}
                );


//unsubscribe all
ngOnDestroy() {
        this.ngUnsubscribe.next();
        this.ngUnsubscribe.complete();
    }
0 голосов
/ 21 января 2019
import { Component, OnDestroy } from '@angular/core';

@Component({...})
export class MyComponent implements OnDestroy {
    ngOnDestroy(): void {
        // called when the component gets destroyed
    }
}

Подробнее о жизненном цикле можно прочитать здесь: https://angular.io/guide/lifecycle-hooks

...