![](/img/trans.png)
[英]Pass child to parent component (child render in router-outlet) ? in Angular?
[英]How to pass data to a child component from parent component when the child component is being called through router-outlet?
我是初学者。 我找不到任何方法。 我尝试使用我在我创建的服务中创建的行为主题。 behaviorSubject 从父组件获取下一个值(this.service.behaviorsub.next(value to pass to child))
然后在子组件中调用 service.behaviorsub,我在子组件中使用 subscribe 来获取数据。 但是当我尝试 console.log 那些数据时,我得到了未定义。
要么有更好的方法将数据从父级传递到子级(通过路由器插座调用),要么可能有更好的方法来使用行为主题。
提前致谢!
代码示例:->父 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)
}
这里记录的数据显示未定义
在这种罕见的情况下,您可以使用驻留在父组件中的提供程序。 使用@Component 装饰器时,您可以初始化一个提供程序(它使用@Injectable 装饰器),您也可以将其注入到通过路由器出口发送的组件中。
然后你可以设置一个你的父母监听的 observable,这可能是一个行为主题。
一个非常简单的例子:
@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.
}
这是处理这种情况的一种方法。 它并不完美,但它有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.