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)广东闲来辅助神器免费版有没有...
大神推荐!欢乐对决辅助软件,微... 大神推荐!欢乐对决辅助软件,微信小程序万能修改器,详细脚本(有挂细节)运微信小程序万能修改器辅助工具...
玩家必看科普!人海大厅挂什么好... 玩家必看科普!人海大厅挂什么好,创思维激k透视插件,详细工具(有挂头条)1、打开软件启动之后找到中间...
热点推荐!多乐跑得私人房间插件... 热点推荐!多乐跑得私人房间插件,拱趴大菠萝修改器,详细器(有挂方针)1、许多玩家不知道多乐跑得私人房...
一秒答解!欢乐茶馆脚本辅助,福... 一秒答解!欢乐茶馆脚本辅助,福建微乐小程序修改器,详细方法(有挂秘笈)1、下载好福建微乐小程序修改器...
一分钟教你!欢乐游戏城攻略,闲... 一分钟教你!欢乐游戏城攻略,闲逸游戏辅助软件下载,详细神器(有挂攻略)1、闲逸游戏辅助软件下载脚本辅...
玩家攻略!人海大厅软件辅助,老... 玩家攻略!人海大厅软件辅助,老k游戏辅助,详细工具(确实有挂)1、上手简单,内置详细流程视频教学,新...