angular无法将值设置给公共变量。
创始人
2024-10-30 01:31:15
0

在Angular中,可以使用服务(Service)来共享数据和状态,而不是直接将值设置给公共变量。以下是一个示例解决方法:

  1. 创建一个服务(service)来共享数据:
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  public sharedValue: any;

  constructor() { }
}
  1. 在需要共享数据的组件中注入该服务:
import { Component } from '@angular/core';
import { DataService } from '路径/data.service';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent {

  constructor(private dataService: DataService) { }

  setValue(value: any) {
    this.dataService.sharedValue = value;
  }
}
  1. 在其他需要访问该共享数据的组件中再次注入该服务,并使用该服务中的共享变量:
import { Component } from '@angular/core';
import { DataService } from '路径/data.service';

@Component({
  selector: 'app-another-example',
  templateUrl: './another-example.component.html',
  styleUrls: ['./another-example.component.css']
})
export class AnotherExampleComponent {
  sharedValue: any;

  constructor(private dataService: DataService) { }

  getValue() {
    this.sharedValue = this.dataService.sharedValue;
  }
}

通过使用服务来共享数据,可以避免直接设置公共变量的问题,并且可以在整个应用程序中共享数据和状态。

相关内容

热门资讯

外挂窍门!fishpoker透... 外挂窍门!fishpoker透视底牌,德州辅助工具到底怎么样-本来存在有辅助技巧(哔哩哔哩)一、德州...
外挂法门!聚星ai辅助工具收费... 外挂法门!聚星ai辅助工具收费多少,德普之星透视辅助插件-本来真的是有辅助软件(哔哩哔哩)外挂法门!...
外挂教材!德普之星私人局透视,... 外挂教材!德普之星私人局透视,大菠萝辅助器-都是真的有辅助工具(哔哩哔哩)运大菠萝辅助器辅助工具,进...
外挂讲义!德普之星有透视辅助吗... 外挂讲义!德普之星有透视辅助吗,aa poker辅助-果然真的有辅助教程(哔哩哔哩)进入游戏-大厅左...
外挂模块!哈糖大菠萝可以开挂吗... 您好,哈糖大菠萝可以开挂吗这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很...
外挂积累!佛手在线大菠萝辅助,... 外挂积累!佛手在线大菠萝辅助,德州透视是真的假的-总是一直总是有辅助软件(哔哩哔哩)1、首先打开德州...
外挂总结!德普之星有辅助软件吗... 外挂总结!德普之星有辅助软件吗,fishpoker透视-一贯是真的有辅助神器(哔哩哔哩)fishpo...
外挂演示!聚星ai辅助工具收费... 外挂演示!聚星ai辅助工具收费多少,约局吧德州可以透视吗-一贯真的是有辅助脚本(哔哩哔哩)1、不需要...
外挂绝活!德普之星透视辅助软件... 外挂绝活!德普之星透视辅助软件,哈糖大菠萝有挂吗5个常用方法-好像是真的有辅助软件(哔哩哔哩)1、起...
外挂指南书!扑克之星辅助,po... 外挂指南书!扑克之星辅助,pokemmo脚本-一贯真的有辅助脚本(哔哩哔哩)1、让任何用户在无需扑克...