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、四川游戏家...
事发当天!aa poker辅助... 事发当天!aa poker辅助包,we-poker正规吗(透视)解密教程(有挂规律)-哔哩哔哩1、每...
不少玩家反映!决战卡五星开挂方... 不少玩家反映!决战卡五星开挂方法,hhpoker一直输有挂吗,绝活教程(有挂方法)-哔哩哔哩1、许多...
推出新举措!pokemmo脚本... 推出新举措!pokemmo脚本辅助器下载,hhpoker是真的假的(透视)关于教程(有挂总结)-哔哩...
针对!新鸿狐辅助软件是真的吗,... 针对!新鸿狐辅助软件是真的吗,随意玩辅助软件,积累教程(揭秘有挂)-哔哩哔哩新鸿狐辅助软件是真的吗是...
透视最新!wepoker买脚本... 透视最新!wepoker买脚本靠谱吗,wepoker怎么买辅助(透视)普及教程(有挂头条)-哔哩哔哩...
于此同时!we-poker软件... 于此同时!we-poker软件,wpk俱乐部是真的吗(透视)总结教程(有挂分析)-哔哩哔哩wpk俱乐...
目前!越乡游义乌透视下载安卓,... 目前!越乡游义乌透视下载安卓,wepoker辅助分析器,经验教程(有挂神器)-哔哩哔哩1、超多福利:...
网友热议!德州局HHpoker... 网友热议!德州局HHpoker透视脚本,epoker透视(透视)专业教程(有挂总结)-哔哩哔哩德州局...
目前!小闲辅助软件,火神大厅科... 目前!小闲辅助软件,火神大厅科技,步骤教程(有挂存在)-哔哩哔哩1、游戏颠覆性的策略玩法,独创攻略技...