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

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

相关内容

热门资讯

透视模拟器!德扑之心免费透视,... 透视模拟器!德扑之心免费透视,德普之星辅助器,2025版教程(有挂教程)1)德扑之心免费透视辅助挂:...
透视玄学!wepoker辅助软... 透视玄学!wepoker辅助软件视频,wepoker智能辅助插件(透视)解说技巧(有挂辅助)1、全新...
透视科技!aapoker真的假... 透视科技!aapoker真的假的,aapoker脚本怎么用,黑科技教程(有挂秘籍)1、构建自己的aa...
透视最新!wepoker黑侠辅... 透视最新!wepoker黑侠辅助器正版下载,wepoker辅助是真的假的(透视)扑克教程(有挂揭秘)...
透视真的!聚星ai辅助工具收费... 透视真的!聚星ai辅助工具收费多少,如何下载德普之星辅助软件,透牌教程(有挂详情)1、游戏颠覆性的策...
透视辅助!wepoker黑侠辅... 透视辅助!wepoker黑侠辅助器,wepoker辅助是真的假的(透视)可靠教程(有挂解密)在进入w...
透视插件!wpk透视是真的吗,... 透视插件!wpk透视是真的吗,wepoker辅助器是真的吗,安装教程(有挂详情)1.wepoker辅...
透视讲解!wepokerplu... 透视讲解!wepokerplus万能挂,wepokerplus透视脚本免费(透视)我来教教你(有挂揭...
透视有挂!拱趴大菠萝万能挂,h... 透视有挂!拱趴大菠萝万能挂,hhpkoer辅助器,揭秘攻略(有挂攻略);1、下载好拱趴大菠萝万能挂辅...
透视辅助!wepoker透视底... 透视辅助!wepoker透视底牌脚本,wepoker有辅助器吗(透视)切实教程(有挂插件)1、上手简...