【问题标题】:how do I use a value saved in service through component in other services in angular 8?如何使用 Angular 8 中通过其他服务中的组件保存在服务中的值?
【发布时间】:2020-10-15 05:36:26
【问题描述】:

我正在尝试通过组件设置值

export class SomeComponent {
constructor(service:SomeService){
  }
count =0 ;
  onRefresh(){
  this.service.count = 1;
  }
}

我想在服务中使用这个值

SomeService{
count:any;
doSomething(){
    //use count value here
    console.log('count value saved thru compoent',count);
    } 
}

我要做的就是在某些服务中使用通过组件存储的值。当我尝试这个时,我得到一个未定义的计数。

【问题讨论】:

    标签: javascript angular angular8 angular-services


    【解决方案1】:

    很难给出一个好的答案,因为我不确定你想要达到什么目标,但这里有一个简单的解决方案,基于提供的信息,没有太多的调整。

    我在 AppComponent HTML 中创建了一个按钮,该按钮将调用一个名为 onRefresh() 的函数,以显示它是如何从函数传递的。单击此按钮后,将运行以下函数:

    <button type="button" (click)="onRefresh()">Count Button in Service</button>

    onRefresh() {
      this.service.count = 1;
      this.service.doSomething();
    }
    

    这是 service.ts 的代码

    import { Injectable } from "@angular/core";
    
    @Injectable({
      providedIn: "root"
    })
    export class SomeServiceService {
      count: any;
    
      doSomething() {
        console.log("count value saved thru compoent", this.count);
      }
    }
    

    否,当您单击该按钮时,它会将服务计数 var 设置为 1,并将其记录到控制台。希望这可以帮助。 Here is a StackBlitz 与上面提供的代码相同

    【讨论】:

      猜你喜欢
      • 2019-09-25
      • 2020-03-29
      • 1970-01-01
      • 1970-01-01
      • 2019-06-09
      • 2013-11-19
      • 2017-12-31
      • 2019-09-26
      • 1970-01-01
      相关资源
      最近更新 更多