gpt4 book ai didi

javascript - 使用共享服务将值传递给兄弟组件

转载 作者:行者123 更新时间:2023-12-03 12:28:47 24 4
gpt4 key购买 nike

我想将选择列表中的值 - ListComponentComponent 传递给兄弟组件 - DisplayComponentComponent 并在 DisplayComponentComponent 的模板中显示该值。我想为此使用共享服务。我创造了服务,我传递了改变的值(value)。但是,当我想在我的显示组件中使用 console.log 这个值时,我什么也看不到。这是我的代码。

显示组件

export class DisplayComponentComponent implements OnInit {
val: any;
constructor(private myService: MyServiceService) { }

ngOnInit() {
this.myService.val.subscribe(result => {
this.val = result
});
}
}

列表

export class ListComponentComponent implements OnInit {
list: any;
selected: string;
constructor(private myService: MyServiceService) { }

ngOnInit() {
this.list = [
{
text: 'test1',
value: 'test1'
},
{
text: 'test2',
value: 'test2'
},
{
text: 'test3',
value: 'test3'
}
]
this.selected = this.list[0].value;
this.myService.update(this.selected);
}
getSelected(val) {
this.selected = val;
this.myService.update(this.selected);
}
}

服务

@Injectable()
export class MyServiceService {
public source = new Subject<any>();
val = this.source.asObservable();

update(input: any) {
this.source.next(input);
}
constructor() { }

}

值应该显示在这里:

<p>
{{result}}
</p>

https://stackblitz.com/edit/angular-7lhn9j?file=src%2Fapp%2Fmy-service.service.ts

最佳答案

如果您想在应用程序加载时显示值,您需要将主题更改为 BehaviorSubject

    private _onChanged: BehaviorSubject<any> = new BehaviorSubject({});
public val= this._onChanged.asObservable();

update(input: any) {
this._onChanged.next(input);
}
constructor() { }

Demo

关于javascript - 使用共享服务将值传递给兄弟组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53913762/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com