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

angular - How to get the value of a variable declared inside a component, to a service file?

如何 access/get 将在组件内声明的变量值添加到服务文件中?我用谷歌搜索了与此主题相关的内容,但找不到与此相关的解决方案

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

变量在服务中声明,您可以在服务和组件以及模板中change/access它,如果您通过按钮增加计数器,更改将反映在服务,因此在组件中。