簡體   English   中英

(Angular)從子級銷毀父級訂閱

[英](Angular) Destroying parent subscriptions from child

//父組件

subscription: Subscription[] = [];

//stuff

constructor(private http: HttpService, private route: ActivatedRoute) {

  const subLoading = this.http.loading.subscribe((loading: boolean) => {
    this.loading = loading;
  });

//stuff to do

   this.subscription.push(subLoading);
   this.subscription.push(subData);
}

ngOnDestroy() {
  console.log("logged if logging out directly from here")
  this.subscription.forEach((sub) => {
    sub.unsubscribe();
  });
}

//子組件

與從子節點到父節點的路由相關聯(父節點 URL:域/列表,例如:子節點 URL:域/列表/項目/53)

//應用路由

const routes: Routes = [
  { path: '', component: AuthComponent },
  { path: 'list/:pageID', component: ListComponent, canActivate: [AuthGuard] },
  {
    path: 'list/item/:id',
    component: ListItemDetailComponent,
    canActivate: [AuthGuard],
  },
];

//標題

    export class HeaderComponent implements OnInit {
  public isLoggedIn = false;
  private userSub: Subscription;

  constructor(private authService: AuthService) {}

  ngOnInit(): void {
    this.userSub = this.authService.user.subscribe((user) => {
      this.isLoggedIn = !!user ? true : false;
    });
  }

  ngOnDestroy(): void {
    this.userSub.unsubscribe();
  }

  logOut() {
    this.authService.logOut();
  }
}

header我取消訂閱,銷毀用戶(行為主體)並注銷

但是如果我在子組件中注銷時,我在父組件中訂閱的許多 BehaviourSubjects不會被破壞

有什么解決辦法嗎?

只是一點,你不會破壞 BehaviourSubjects,你會破壞訂閱,這就是為什么其他訂閱了相同 behaviorSubject 的組件會保留它們的訂閱。 我認為您可以在注銷時使用其他主題發出,並在每個訂閱中使用它,使用 takeUntil() 運算符。 采取Until rxjs 算子示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM