首页 文章

使用@Input和router-outlet的Angular2 . 处理ngrx / store中的路由哑组件

提问于
浏览
1

所以,我有一个容器组件“ Profile " that has a navigation inside - switching tabs like " Info ", " Favourites ", " PublishedArticles ” .

我正在加载那些带有路由器插座和子路径的选项卡“ /info ", " /favourites ", " /articles ” . 一旦router-outlet导航到cub-component,我想将加载的Profile状态的片段传递给它 .

我刚刚意识到正常的@Input不会在没有太多重组的情况下以某种方式整齐地实现它的解决方案 .

将状态与路由器插座加载的哑组件(子路由)进行通信的最佳方法是什么?或者,可能,您通常如何处理这种情况?

1 回答

  • 0

    我会将 Service 注入到共享相同数据的所有组件中,如下所示:

    @Injectable()
    export class SharedDataService {
      someData:Object={}
      constructor() {
    
      }
    }
    

    然后,在组件中,您可以使用 Router 服务侦听导航更改,以便更新组件和UI中的数据 .

    import {Component,OnInit} from '@angular/core';
    import {NavigationEnd, Router} from "@angular/router";
    import {SharedDataService} from "../shared-data.service";
    @Component({
      selector: 'profile',
      templateUrl: './profile.component.html',
      styleUrls: ['./profile.component.css']
    })
    export class Profile implements OnInit {
      someData:Object;
    
      constructor(private sharedDataService: SharedDataService, private router:Router) {
        this.someData = this.sharedDataService.someData;
        this.router.events.subscribe((val)=>{
          if(val instanceof NavigationEnd){
              //update the shared data when this page is being navigated to
              this.someData=this.sharedDataService.someData;
          }
        });
      }
    }
    

相关问题