【问题标题】:Angular2 using @Input with router-outlet. Handling routed dumb components in ngrx/storeAngular2 使用带有路由器出口的@Input。在 ngrx/store 中处理路由的哑组件
【发布时间】:2017-05-10 07:29:35
【问题描述】:

所以,我有一个容器组件“Profile”,里面有一个导航 - 切换标签,如“Info”、“收藏夹”、“PublishedArticles”。

我目前正在加载那些带有路由器插座和子路由的选项卡,它们位于“/info”、“/favourites”、“/articles”。一旦 router-outlet 导航到 cub-component,我想将加载的 Profile 状态的切片传递给它。

我刚刚意识到普通的 @Input 无法以这种方式(通过路由器出口)加载愚蠢的组件。现在我正在寻找一种解决方案,以一种巧妙的方式实现它,而无需进行过多的重组。

向路由器出口加载的哑组件(子路由)传达状态的最佳方式是什么?或者,您通常会如何处理这种情况?

【问题讨论】:

  • 看看this one。使用提供者在Components之间共享数据
  • 似乎解决此问题的一般方法是(a)在组件之间创建共享服务并在它们之间绑定变量数据,或者如果您不需要数据绑定:(b)通过通过路由参数的值

标签: angular data-binding redux angular2-routing ngrx


【解决方案1】:

我会创建一个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;
      }
    });
  }
}

【讨论】:

    猜你喜欢
    • 2016-11-13
    • 2016-11-16
    • 1970-01-01
    • 2017-07-19
    • 2016-12-09
    • 1970-01-01
    • 2023-03-28
    • 2017-02-15
    • 1970-01-01
    相关资源
    最近更新 更多