我創建了一個包含簡單字串變數的 Angular 服務,然后在這個服務中我更新了它在函式中的值。然后我在我的 component.ts 中呼叫這個函式(通過依賴注入),我得到了我的變數的初始值(目標是獲取更新的值)
這是服務:
import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import { HttpService } from '../http/http.service';
@Injectable({
providedIn: 'root',
})
export class MyService {
constructor() {}
callLogsToggle = 'on';
這是在此服務中創建的功能
public setHubspotTogglesStatus() {
this.callLogsToggle = 'off'; //updated to off
}
這是我的 component.ts
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'my-selector',
templateUrl: './myCompo.component.html',
styleUrls: ['./myCompo.component.sass'],
})
export class MyComponent implements OnInit {
constructor(
private mySevice: MyService,
) {
this.myService.setHubspotTogglesStatus()
console.log(this.mySevice.callLogsToggle) //The result is "on"
//The variable is not
//updated
}
那么對解決這個小問題有什么幫助嗎?
uj5u.com熱心網友回復:
您的方法需要 2 個引數,但您使用 0 呼叫它,嘗試洗掉函式的引數并在您的建構式中呼叫它或為其傳遞預期的引數。
在您呼叫的服務函式上列印任何值,以檢查它是否正確到達該函式。
uj5u.com熱心網友回復:
在您的服務檔案中
import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import { HttpService } from '../http/http.service';
@Injectable({
providedIn: 'root',
})
export class MyService {
callLogsToggle:string;
constructor() {
this.callLogsToggle = 'on';
}
public setHubspotTogglesStatus() {
this.callLogsToggle = 'off'; //updated to off
}
public getcallLogsToggle():string {
return this.service.callLogsToggle;
}
}
在您的組件中
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'my-selector',
templateUrl: './myCompo.component.html',
styleUrls: ['./myCompo.component.sass'],
})
export class MyComponent implements OnInit {
constructor( private mySevice: MyService) {}
ngOnInit(): void {
this.myService.setHubspotTogglesStatus();
console.log(this.mySevice.getcallLogsToggle());
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/365774.html
標籤:javascript 有角的 打字稿 服务 成分
上一篇:單例服務上的資料傳播
下一篇:角度資料源過濾器
