【问题标题】:How to pass data to a child component from parent component when the child component is being called through router-outlet?通过router-outlet调用子组件时,如何将数据从父组件传递给子组件?
【发布时间】:2020-06-06 10:52:33
【问题描述】:

我是初学者。我找不到任何办法。我尝试使用在我创建的服务中创建的行为主题。 behaviorSubject 从父组件获取下一个值(this.service.behaviorsub.next(value to pass to child))

然后在子组件中调用 service.behaviorsub,我使用 subscribe 来获取数据。但是当我尝试控制台记录该数据时,我得到了不确定。

要么有更好的方式将数据从父级传递给子级(通过路由器出口调用),要么有更好的方式来使用 behaviorSubject。

提前致谢!

代码示例: ->父母 html

    <div class="container" *ngIf="outlet.isActivated == false">
    <div class="row">
       <div class="col" *ngFor="let item of items">
         <app-another-component [Item]="item" (click)="should-take-to-another- 
     component-for-which-there-is-router-outlet()"></app-another-component>
    </div>
   </div>
   <div class="container">
     <router-outlet  #outlet="outlet"></router-outlet>
   </div>

app-another-component 具有某些详细信息,例如标题和图像,单击它们应该会打开另一个仅具有该特定标题和图像的组件(并且此标题不会显示为查询参数)。

对于行为主体: 在服务文件中:

behavior: new BehaviorSubject<type>(value);

在父文件中:

should-take-to-another-component-for-which-there-is-router-outlet(data:type){
this.service.behavior.next(data);
}

在文件中(这是孙子,但通过路由,它只打开这个文件)

ngOnInIt(){
 this.service.behavior.subscribe((data) => {
  console.log(data)
}

这里记录的数据显示未定义

【问题讨论】:

  • 你能贴一些代码吗?
  • 请提供代码示例
  • 使用 BehaviourSubject 是一个很好的方法,您也可以发布与此相关的代码
  • 您可以在角度路由中检查解析器,它可能会对您有所帮助。

标签: angular router-outlet


【解决方案1】:

在这种极少数情况下,您可以使用驻留在父组件中的提供程序。 使用@Component 装饰器时,您可以初始化一个提供程序(它使用@Injectable 装饰器),您也可以将其注入到路由出口中发送的组件中。

然后你可以设置一个你的父母收听的可观察对象,这可能是一个行为主体。

一个非常简单的例子:

@Injectable()
export class MyOutputter {

private thelistener$ = new BehaviorSubject<TheDataObjectYouWant>(null);

get listener$() {
return this.thelistener$.asObservable();
}

setTheOutputValue (value: TheDataObjectYouWant) { // or use a setter. I prefer a method, but this is more flavor imo.
this.thelistener$.next(value);
}

}

在您的母组件中(包含路由器插座的组件):

@Component({ // skipping template and styles and selector.
providers: [MyOutputter]
})
export class MotherComponent{

constructor(private myOutputter: MyOutputter) {
// setup listening and subscription of the getter here and do what you want it to do when receiving
}

}

在输出中使用的组件中

@Component({}) // skipping the template and stuff
export class ChildOutputComponent {

constructor(private outputter: MyOutputter) {}

// use this.outputter.setTheOutputValue() wherever you need to send the output.

}

这是处理此问题的一种方法。它并不完美,但它确实有效。

【讨论】:

  • 感谢您的建议。我已经尝试过了,但这不起作用。当我 next() 父组件中的行为主题,然后在孙子组件中订阅它时,console.log 会给出未定义的数据。虽然,如果我尝试 next() 孙子本身的 behaviorSubject,我可以 console.log() 数据。
  • 你能展示一下你是如何做到这一点的吗?更容易发现问题所在。
  • 看看这个:stackblitz.com/edit/angular-crls4x你可以忽略第二个输出。 stackblitz 现在存在的问题是我在路由器内部有 appcomponent 以及它被引导。引导的 AppComponent 有它自己的提供者,但该提供者实例没有连接到其他组件。然而,路由器中的第二个连接到孩子和孙子。重点是说明您可以使用提供程序以这种方式获取数据。
猜你喜欢
  • 2022-10-13
  • 2017-05-18
  • 2020-05-27
  • 2020-11-01
  • 1970-01-01
  • 2019-01-07
  • 2021-09-12
  • 2019-10-05
  • 2019-01-13
相关资源
最近更新 更多