簡體   English   中英

角路由器使用相同的組件

[英]Angular Router Use Same Component

我有兩個頁面,我想為兩個路徑中的每一個使用相同的組件。 原因是我共享標題,該標題具有兩個主要組件的搜索字段。 每當我更改頁面時,都會不斷收到對該服務的其他呼叫。 第一次2,第二次4,第三次6 ...我只希望頁面重新開始。 這就是構造函數正在發生的事情。 我要做的就是根據路線網址顯示/隱藏庫和詳細信息頁面。

  this.router.events.subscribe((val) => {
      if (val instanceof NavigationEnd) {
          let urlArray = val.url.split('/');
          if (urlArray[1] === 'library') {
              this.detail = false;
          } else if (urlArray[1] === 'detail') {
              this.searchById(urlArray[2]);
          }
      }
  });

基本上,圖書館組件有一個書單,單擊后會轉到該書的詳細信息頁面。 我顯示/隱藏庫和詳細信息頁面

const appRoutes: Routes = [
  { path: 'library', component: LibraryComponent },
  { path: 'detail/:id',      component: LibraryComponent },
  { path: '',   redirectTo: '/library', pathMatch: 'full' }
];

這是服務調用,它只返回dummyJSON數據

  searchById(id)  {

  this.mainService.searchById(id).subscribe(
      data => { this.detail = true; this.bookdata = data; console.log(data); },
      err => { },
          () => { }
)};

您的代碼中存在訂閱泄漏,請將其更改為以下內容

  private unsubscribeAll: Subject<any> = new Subject<any>();

  ngOnDetroy() {
     this.unsubscribeAll.next();
     this.unsubscribeAll.complete();
  }


  ...
  this.mainService.searchById(id)
    .pipe(
       takeUntil(this.unsubscribeAll)
    )
    .subscribe(
      data => { this.detail = true; this.bookdata = data; console.log(data); },
      err => { },
          () => { }
    );

   ...

回來之后,我只是取消了路由器事件的訂閱。

      const routerEvent = this.router.events.subscribe((val) => {
      if (val instanceof NavigationEnd) {
          let urlArray = val.url.split('/');
          if (urlArray[1] === 'library') {
              this.detail = false;
          } else if (urlArray[1] === 'detail') {
              this.searchById(urlArray[2]);
          }
          routerEvent.unsubscribe();
      }
  });

暫無
暫無

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

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