【问题标题】:wrong result when I pass a value from a service to my angular component当我将值从服务传递到我的角度组件时,结果错误
【发布时间】:2022-01-03 08:18:03
【问题描述】:

我创建了一个 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
}

这是我的组件.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
    
}

那么对于解决这个小问题有什么帮助吗?

【问题讨论】:

  • 什么时候调用方法来更新变量?您只打印构造函数的变量值,这意味着您将只打印初始值。如果你想看到变量的变化,你必须在另一个地方打印它
  • 我在我的原始代码中做了,问题总是一样

标签: javascript angular typescript service components


【解决方案1】:

在您的服务文件中

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;
  }
}

在您的 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) {}

ngOnInit(): void {
   this.myService.setHubspotTogglesStatus();
   console.log(this.mySevice.getcallLogsToggle());
 }

}

【讨论】:

    【解决方案2】:

    您的方法需要 2 个参数,但您使用 0 调用它,尝试删除函数的参数并在构造函数中调用它或传递预期的参数。

    在您调用的服务函数上打印任何值,以检查它是否正确到达该函数。

    【讨论】:

    • 维克多,我完全按照你说的做了,当我在更新后在服务中打印变量时,它向我显示了正确的结果(更新的值),但是当我在 component.ts 中打印它时,它显示了我的初始值
    • 你能尝试创建一个闪电战来重现它吗?
    猜你喜欢
    • 2020-04-08
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 2011-10-10
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多