簡體   English   中英

如何在 Angular 的不同組件中使用注入服務的相同實例?

[英]How to use same instance of an injected service across different components in Angular?

我目前正在嘗試從不同組件訪問服務中變量的實時值。

在我的服務中,我有:

export class ServiceA {
  serviceVar = "hello";

  constructor(private httpClient: HttpClient) {
  }

  getServiceVar(){
    return this.serviceVar
  }

  setServiceVar(newVar){
    this.serviceVar = newVar;
  }

在組件 AI 中有:

export class ComponentA implements OnInit {
  constructor(private service: ServiceA) {}

  setVar() {
    this.service.setServiceVar("new value from A")
  }

  getVar(){
    console.log(this.service.getServiceVar())
  }
}

在組件 BI 中有:

export class ComponentB implements OnInit {
  constructor(private service: ServiceA) {}

  setVar() {
    this.service.setServiceVar("new value from B")
  }

  getVar(){
    console.log(this.service.getServiceVar())
  }

}

在 app.module.ts

providers: [ServiceA]

如果我在 ComponentA 中設置變量,我希望以某種方式更新 ServiceA 的變量,以便如果 ComponentB 嘗試 get() 該值,它會收到 ComponentA 更新服務所用的值。 本質上讓 ComponentA 和 ComponentB 使用相同的服務實例。

現在發生的事情是有 2 個 ServiceA 實例,當 ComponentA 運行 setVar() 時,更改僅應用於 ComponentA 的服務實例,而不應用於 ComponentB 的服務實例。

我可以看到你的代碼是完全正確的,因為你已經注冊了服務 app.module.ts。 所以,會有一個服務的單例實例。

您唯一需要更正的是服務類,您需要在其中添加名為電子表格 ID 的屬性。 強文本

export class ServiceA {
  serviceVar = "hello";
  spreadsheetID

  constructor(private httpClient: HttpClient) {
  }

  getServiceVar(){
    return this.spreadsheetID
  }

  setServiceVar(newSpread){
    this.spreadsheetID = newSpread;
  }

答案是讓你的服務成為一個提供者,就像我在我的問題中所做的那樣......但也要確保你刪除

@Injectable({
  providedIn: 'root'
})

並將其更改為:

@Injectable()

在您的服務之上:)

暫無
暫無

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

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