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

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