在两个不相关的组件之间通信数据

时间:2019-10-15 22:10:50

标签: angular

我有一个存储在无序列表中的列表,初始化此列表时,<li class="nav-item"> <div class="dropdown {{showMenu ? 'show' : ''}}"> <button (click)='toggleMenu()' class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded=""> Stores </button> <div class="dropdown-menu {{showMenu ? 'show' : ''}}" aria-labelledby="dropdownMenu2"> <button (click)="clickStore()" class="dropdown-item" type="button" [routerLink]="['/store/1']">Store 1</button> <button (click)="clickStore()" class="dropdown-item" type="button" [routerLink]="['/store/2']">Store 2</button> <button (click)="clickStore()" class="dropdown-item" type="button" [routerLink]="['/store/3']">Store 3</button> <button (click)="clickStore()" class="dropdown-item" type="button" [routerLink]="['/store/4']">Store 4</button> <button (click)="clickStore()" class="dropdown-item" type="button" [routerLink]="['/store/5']">Store 5</button> <button (click)="clickStore()" class="dropdown-item" type="button" [routerLink]="['/store/6']">Store 6</button> <button (click)="clickStore()" class="dropdown-item" type="button" [routerLink]="['/store/7']">Store 7</button> <button (click)="clickStore()" class="dropdown-item" type="button" [routerLink]="['/store/8']">Store 8</button> <button (click)="clickStore()" class="dropdown-item" type="button" [routerLink]="['/store/9']">Store 9</button> <button (click)="clickStore()" class="dropdown-item" type="button" [routerLink]="['/store/10']">Store 10</button> <button (click)="clickStore()" class="dropdown-item" type="button" [routerLink]="['/store/11']">Store 11</button> <button (click)="clickStore()" class="dropdown-item" type="button" [routerLink]="['/store/12']">Store 12</button> </div> </div> </li> 函数将返回所有存储的数据。单击每个列表元素时,我想将商店数据发送到商店详细信息组件,以便它可以计算出合适的数据来显示。由于这两个组成部分不遵循父/子关系,该怎么办?我是最新版本的Angular的新手,所以我不确定,也许要使用发射器或Rxjs吗?

我的模板:

ngOnInit() {
    this.storeService.getStores().subscribe({ 
        next: stores => {
            this.stores = stores;
        },
        error: err => this.errorMessage = err
    });
}



clickStore(): void {
    console.log(this.stores);
    // send "this.stores" to store detail component
}

我的商店列表组件:

export class StoreDetailComponent implements OnInit {

  retrieveStoreData(): void {
     // get data from store list component and assign to this.stores
  }


   displayStore(): void {
       let id = +this.route.snapshot.paramMap.get('id');

       for(let i=0;i<this.stores.length; i++){
          if(this.stores[i].storeId == id){
            this.store = this.stores[i];
          }
       }
   }


}

我的商店详细信息组件:

ID: {{store.storeId}}

Name: {{store.storeName}}

Description: {{store.storeDescription}}

在商店详细信息模板中,我只想显示商店数据:

import re
re.search(r'(time:\(.*\)\))', s).group(1)

1 个答案:

答案 0 :(得分:2)

您应该使用服务来检索数据并将其存储在本地属性中。这样,您可以通过将服务注入组件来访问它。是的,状态管理解决方案可以工作,但是,对于这种简单的用例,简单的可注入服务就能解决问题。