当通过路由器出口调用子组件时,如何将数据从父组件传递给子组件



我是个初学者。我找不到任何办法。我尝试使用我在创建的服务中创建的行为主题。behaviorSubject从父组件(this.serve.behaviorssub.next(传递给子组件的值((中获取下一个值

然后在子组件中调用service.behaviorsub,我使用subscribe来获取数据。但当我尝试console.log数据时,我得到了未定义的结果。

要么有一种更好的方法将数据从父级传递到子级(通过路由器出口调用(,要么有一个更好的方法来使用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>

应用程序另一个组件有某些详细信息,如标题和图像,点击它应该只打开另一个具有特定标题和图像的组件(该标题不会显示为查询参数(。

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

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装饰器(,也可以将其注入在路由器出口中发送的组件中。

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

一个非常简单的例子:

@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.
}

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

最新更新