【问题标题】:Angular 5 Data Access to Component from one of the component's child从组件的一个子组件对组件的 Angular 5 数据访问
【发布时间】:2018-06-12 20:35:24
【问题描述】:

我有以下组件结构;

  • RecipeDetailComponent
  • 配方列表组件
    • RecipeItemComponent(此组件是 RecipeList 的子组件)
  • 配方组件

并且想要将数据RecipeItemComponent 传递给RecipeDetailComponent。 主要的方法是在 RecipeItemComponent 创建@Output(),从RecipeListComponent 获取数据并使用@Output()。最后使用属性绑定通过RecipeComponent 使用@input() 从RecipeDetailComponent 获取数据。

有没有有效的方法或简单的方法来做到这一点?我们是否必须越过父组件才能从子组件获取数据到 RecipeDetailComponent?

提前致谢

【问题讨论】:

  • RecipeDetailComponent 提供服务,将其注入RecipeItemComponent 并使用它来传递数据(最好使用可观察对象)
  • RecipeList 组件是RecipeDetail 的子组件吗?我不这么认为。如果不是,那么您不能为此使用@output。您只能将输出用于 recipeItem 到 RecipeList
  • 最好的方法是在这些组件之间使用共享服务

标签: angular angularjs-directive angular-components angular5


【解决方案1】:

我的解决方案是创建一个通用的配方服务,它已将参数作为 Subject 类型的对象传递,并将此服务注入父组件和子组件中,当我导航到子组件时,我会通知

/// service 


export class SharedService {
  passedParamter: Subject<any> = new Subject<any>();

  notify(data) {
    this.passedParamter.next(data);
  }
}


//// in parent Component

@Component({
    ...,
   providers:[SharedService]
})

export class RecipeListComponent implements OnInit {
   constructor(private SharedService: SharedService){}

   ngOnInit() {
   }

   navigateToChild() {
       this.SharedService.notify(data);
   }
}


//// in child Component

.
.
.
export class RecipeItemComponent implements OnInit {
    constructor(private SharedService: SharedService){}
    ngOnInit() {
        this.SharedService.passedParamter.subscribe(
           data => {
                /// here you will recive the data
            }
        )
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-01
    • 2016-09-28
    • 1970-01-01
    • 2020-04-14
    • 2017-03-17
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多