gpt4 book ai didi

angular - 如何在不相关的组件之间传递数据 angular 10

转载 作者:行者123 更新时间:2023-12-04 08:16:48 24 4
gpt4 key购买 nike

我想将选择值的 id 传递给另一个不相关的组件

组件 1:

HTML

<select (change)="getSelectedStoreId($event.target.value)">
<option *ngFor="let store of stores.slice().reverse()" value="{{store.id}}">
{{store.name}}
</option>
</select>

storeId: any;
getSelectedStoreId(store: any) {
this.storeId = store;
}

组件 2:

loadItemByStore(storeId: number) {
this.service.getItemByStore(storeId).subscribe((res:
HttpResponse<Item[]>) => {
this.data= res.body || [];
});
}

最佳答案

使用带有 SubjectBehaviorSubject 的共享服务,像这样:

// service.ts

@Injectable({
providedIn: 'root'
})
export class MyService {
sharedValue$ = new Subject();
}

// component a

@Component({
...
})
export class ComponentA implements OnInit {
constructor(private myService: MyService) {
}

ngOnInit() {
// get data
this.myService.sharedValue$.subscribe(data => {
// data will update here upon changes
console.log(data) // 100
})
}


}

// component b

@Component({
...
})
export class ComponentB implements OnInit {
constructor(private myService: MyService) {
}

ngOnInit() {
// set data
this.myService.sharedValue$.next(100)
}


}

关于angular - 如何在不相关的组件之间传递数据 angular 10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65670751/

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