微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angular-如何获取在组件内部声明的变量的值到服务文件?

如何解决angular-如何获取在组件内部声明的变量的值到服务文件?

如何访问/获取组件内部声明的变量的值到服务文件?我在Google上搜索了与此主题相关的内容,但找不到与此相关的任何解决方

mylib.component.ts

import { Component,Input } from '@angular/core';

@Component({
  selector: 'srr-mylib',template: `
    <h1> {{counter}} </h1>
    <button class="btn btn-primary" (click)=counterIncrease()>Increase</button>
  `,styles: [
  ]
})
export class MylibComponent implements OnInit {

  counter: number = 0   // this is the variable that I need to get/access
                        // from the service file
  constructor( ) {}

  ngOnInit(){
   
  }

  counterIncrese() {
    this.counter = this.counter + 1;
  }
  
}

mylib.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class MylibService { 

  constructor() { }

  getCounter(){
    //This is function that need to use that 'counter' variable
  }
}

解决方法

对于应该在服务中处理并可以在组件中访问的变量,通常应该采用另一种方法,即在服务中声明变量并将服务导入组件中:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class MylibService { 

counter: number = 0   // this is the variable

  constructor() { }

}
import { Component,Input } from '@angular/core';

//import { MylibService } from 'path to the service'

@Component({
  selector: 'srr-mylib',template: `
    <h1> {{this.service.counter}} </h1>  <!--use it in your page-->
    <button class="btn btn-primary" (click)=counterIncrease()>Increase</button>
  `,styles: [
  ]
})
export class MylibComponent implements OnInit {

  counter: number = 0   //<---this is the variable

  constructor(private service: MylibService) {} //<--- import the service

  ngOnInit(){
   
  }
  counterIncrease() {
    this.service.counter++; //<---set it
  }
  
}

变量在服务中声明,您可以在服务和组件以及模板中对其进行更改/访问,如果通过按钮增加计数器,则更改将反映在服务中,因此在组件中。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。