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

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

相关内容

热门资讯

最新技巧!wepokerplu... 最新技巧!wepokerplus脚本(辅助挂)都是是真的有挂(果真有挂辅助工具)1、游戏颠覆性的策略...
分享个大家!wepoker高级... 分享个大家!wepoker高级辅助(辅助挂)好像是真的有挂(有挂攻略辅助软件)1、模拟器是什么优化,...
教学盘点!wpk显示有作弊(辅... 教学盘点!wpk显示有作弊(辅助挂)竟然真的是有挂(有挂分享辅助方法)1、玩家可以在透视最简单三个步...
重磅来袭!wejoker内置辅... 重磅来袭!wejoker内置辅助(辅助挂)果然真的有挂(有挂头条辅助攻略)1、该软件可以轻松地帮助玩...
重大通报!wepoker怎么开... 重大通报!wepoker怎么开辅助(辅助挂)一贯真的有挂(有挂攻略辅助器)1、任何透视是真的假的的玩...
推荐十款!poker worl... 推荐十款!poker world辅助器(辅助挂)确实是有挂(真实有挂辅助教程)1)免费钻石:进一步探...
玩家必看秘籍!wepoker有... 玩家必看秘籍!wepoker有辅助插件吗(辅助挂)原来有挂(有挂技巧辅助脚本)该软件可以轻松地帮助玩...
一分钟揭秘!wepoker有什... 一分钟揭秘!wepoker有什么规律(辅助挂)原来真的是有挂(有挂解密辅助工具)1、全新机制【ai辅...
玩家必备教程!wepoker私... 玩家必备教程!wepoker私人局透视教程(辅助挂)其实真的有挂(有挂方式辅助教程)1、点击下载安装...
必备教程!聚星ai辅助工具下载... 必备教程!聚星ai辅助工具下载(辅助挂)原来有挂(揭秘有挂辅助工具)该软件可以轻松地帮助玩家将外卦神...