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

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

相关内容

热门资讯

重大科普!hhpoker真能买... 1、重大科普!hhpoker真能买到挂吗,wepoker手机助手,新2025版(有挂软件)2、进入游...
揭秘真相!wepoker买脚本... 揭秘真相!wepoker买脚本靠谱吗,hh poker软件,微扑克教程(有挂透视);支持2-10人实...
一分钟带你了解!德普之星辅助软... 一分钟带你了解!德普之星辅助软件,聚星ai辅助工具收费多少,透牌教程(有挂透明);人气非常高,ai更...
一分钟了解!拱趴大菠萝开挂方法... 一分钟了解!拱趴大菠萝开挂方法,sohoo poker辅助,介绍教程(有挂透明)是由北京得拱趴大菠萝...
玩家必看秘籍!wepoker怎... 玩家必看秘籍!wepoker怎么增加运气,wepokerplus开挂,玩家教你(有挂攻略);玩家必备...
三分钟了解!hhpoker辅助... 三分钟了解!hhpoker辅助器,hh poker透视器下载,教你攻略(有挂技巧);人气非常高,ai...
科技介绍!如何下载wepoke... 科技介绍!如何下载wepoker安装包,wpk透视是真的假的,透明教程(有挂攻略)科技教程也叫必备教...
玩家必备科普!wepoker作... 玩家必备科普!wepoker作弊方法,we poker辅助器下载,透牌教程(有挂教程);致您一封信;...
揭秘一下!wepoker俱乐部... 揭秘一下!wepoker俱乐部辅助器,wepoker辅助软件视频,教你攻略(有挂技巧)这是由厦门游乐...
今日百科!wepoker怎么破... 今日百科!wepoker怎么破解游戏,sohoo poker辅助器,解密教程(有挂软件);wepok...