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、完成德扑圈有辅助插件,帮助玩家取得...
玩家必看科普!aapoker辅... 玩家必看科普!aapoker辅助挂多功能透视工具,竟然真的有挂(有挂功能)1、完成aapoker有辅...
一起来讨论!智星德州扑克辅助挂... 一起来讨论!智星德州扑克辅助挂多功能透视工具,其实有挂(竟然有挂)1.智星德州扑克 选牌创建新账号,...
最新通报!AAPoKer辅助挂... 最新通报!AAPoKer辅助挂多功能透视工具,确实有挂(有挂方法)小薇(辅助器软件下载)致您一封信;...
推荐一款!wepoker辅助挂... 您好,wepoker这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家...
每日必看教程!wpk辅助挂多功... 每日必看教程!wpk辅助挂多功能透视工具,好像是有挂(有挂规律)1.wpk 选牌创建新账号,点击进入...
重磅来袭!aapoker辅助挂... 重磅来袭!aapoker辅助挂多功能透视工具,其实是真的有挂(有挂解密)1、完成aapoker辅助器...
一分钟揭秘!红龙poker辅助... 一分钟揭秘!红龙poker辅助挂多功能透视工具,本来存在有挂(有挂技巧)1、红龙poker辅助器安装...
推荐几款新版!智星菠萝德州辅助... 推荐几款新版!智星菠萝德州辅助挂多功能透视工具,其实有挂(有挂实锤)1、玩家可以在智星菠萝德州线上大...
最新技巧!智星菠萝德州辅助挂多... 最新技巧!智星菠萝德州辅助挂多功能透视工具,一直是真的有挂(有挂解密)1、智星菠萝德州模拟器是什么优...