我是初学者。我找不到任何办法。我尝试使用在创建的服务中创建的“行为”主题。 behaviorSubject从父组件中获取下一个值(this.service.behaviorsub.next(要传递给子级的值))
然后在子组件中调用service.behaviorsub,我在其中使用subscribe获取数据。但是当我尝试console.log该数据时,我却无法定义。
或者有更好的方法将数据从父级传递到子级(通过router-outlet调用),或者有更好的方法来使用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)
}
这里记录的数据显示未定义
答案 0 :(得分:0)
在这种极少数情况下,您可以使用驻留在父组件中的提供者。 使用@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.
}
这是处理此问题的一种方法。这不是完美的,但可以。