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

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

相关内容

热门资讯

指导大家!雀魂麻将,小程序雀神... 1、指导大家!雀魂麻将,小程序雀神麻将规律,新2024版(有挂头条);详细教程。2、雀魂麻将透视辅助...
7分钟普及!科乐麻将助赢神器,... 自定义微信小程序系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅助器,不管你是想...
玩家必备科普(wpk教程)外挂... 自定义wpk教程系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅助器,不管你是想...
热点讨论!顺欣茶坊辅助,广东雀... 热点讨论!顺欣茶坊辅助,广东雀神麻雀辅助器在哪里下载,新版2024教程(确实有挂);是一款可以让一直...
8分钟实锤!开心联盟牛牛辅助器... 8分钟实锤!开心联盟牛牛辅助器(透视)外挂透视辅助器(2023已更新)(哔哩哔哩),您好,这款游戏可...
透明教学(德州版wpk)外挂透... 透明教学(德州版wpk)外挂透明挂辅助软件(透视)透视辅助(2022已更新)(哔哩哔哩)1、这是跨平...
十分钟了解!欢聚水鱼虎步龙行辅... 十分钟了解!欢聚水鱼虎步龙行辅助器真的,微信小程序雀神有外挂码,总结教程(讲解有挂);1.欢聚水鱼虎...
十分钟科普!胡乐麻将神器免费下... 十分钟科普!胡乐麻将神器免费下载,广东雀神麻雀调胜率,详细教程(有挂技巧)您好,胡乐麻将,确实是有挂...
透视好友(pokermaste... 透视好友(pokermaster)软件透明挂辅助器安装(辅助挂)辅助透视(2021已更新)(哔哩哔哩...
实测揭晓!中至余干麻将有挂,广... 实测揭晓!中至余干麻将有挂,广东雀神麻雀辅助器下载,普及教程(有挂秘笈)是一款可以让一直输的玩家,快...