[英]Angular share data between components using service
我正在嘗試使用服務在組件之間共享數據。 在project
組件中,按鈕上有一個單擊事件
<button type="submit" (click)="newValue()" class="btn btn-warning btn-sm mt-2">Create task</button>
它應該發出一個字符串值
newValue() {
this.shareService.changeValues("Hello from project");
}
在服務中,我試圖在BehaviorSubject
上獲得一個observable
private selectedValue = new BehaviorSubject<string>("");
currentValue = this.selectedValue.asObservable();
Task
組件已訂閱,但值未更新。
在服務中,當調用changeValues
方法時,您需要對BehaviorSubject
即BehaviorSubject
執行.next
。 請參考下面的代碼
在ShareService
changeValues(value: string) {
this.selectedValue.next(value);
}
更好的處理方法是返回Observable
,我們可以訂閱它來獲取值。
@Injectable()
export class ShareService{
selectedValue = new BehaviorSubject<string>("");
getSelectedValue$() {
return this.selectedValue.asObservable();
}
changeValues(value: string) {
this.selectedValue.next(value);
}
}
無論我們在哪里需要SelectedValue
,我們都會注入這個Service
並subscribe
從getSelectedValue$
方法返回的Observable
。 在Task
組件中
export class TaskComponent implements OnInit {
constructor(
public ShareService: ShareService) {
}
ngOnInit(): void {
this.ShareService.getSelectedValue$().subscribe((selectedValue)=> {
// use selectedValue here
})
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.