簡體   English   中英

Angular 7:無法從組件之間共享的服務中獲取價值

[英]Angular 7: Unable to get the value from service which is shared between components

我有一個帶有 setter 和 getter 的服務類

@Injectable()
export class DataService {
    name: string;

    getName(): string {
       return this.name
    }

    setName(newname: string) {
        this.name = newname;
    }

}

我也在 app.module 中定義了這個

providers: [ DataService ]

並在一個組件中設置一個名稱並嘗試從另一個組件中檢索。 我得到未定義。

您的組件可能會在任何有機會調用setName之前調用getName 您可能正在ngOnInit執行此ngOnInit 我建議你試試這個 Subject-Observable 模式(不要忘記從 rxjs 導入你需要的任何東西):

服務.ts

name: string; // not always necessary/desired
nameSub: BehaviorSubject<string> = new BehaviorSubject(''); // initializing with empty string--could be anything you want
getName: Observable<string> = this.nameSub.asObservable();

setName (name: string) {
  this.name = name; // not always necessary/desired
  this.nameSub.next(name);
}

任何組件.ts

myName: string;
sub: Subscription;

ngOnInit () {
  this.sub = dataService.getName.subscribe(name => {
    // assign name to local variable or class property, for example:
    this.myName = name;
  });
}

inputHandler (event) {
  // calling this method will automatically update `myName` through the subscription in ngOnInit!
  dataService.setName(event.name);
}

// Don't forget to unsubscribe when you create your own subscriptions
ngOnDestroy () {
  this.sub.unsubscribe();
}

這種模式允許你將狀態保存在一個地方(服務),但也可以通過利用 RxJs Observables 在任何變化的時刻通知其他任何地方。

您可以在此處閱讀有關 BehaviorSubjects 和其他內容的信息: http : //reactivex.io/rxjs/manual/overview.html#behaviorsubject

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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