簡體   English   中英

Angular 使用服務在組件之間共享數據

[英]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方法時,您需要對BehaviorSubjectBehaviorSubject執行.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 ,我們都會注入這個ServicesubscribegetSelectedValue$方法返回的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM