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

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

相关内容

热门资讯

2分钟了解!杭州边锋辅助软件!... 2分钟了解!杭州边锋辅助软件!竟然是真的有辅助技巧(确实有挂)-哔哩哔哩1、杭州边锋辅助软件辅助软件...
第6分钟了解!闲来辅助神器!其... 第6分钟了解!闲来辅助神器!其实有辅助插件(有挂头条)-哔哩哔哩1)闲来辅助神器辅助插件:进一步探索...
第2分钟了解!白金岛十胡卡辅助... 第2分钟了解!白金岛十胡卡辅助!确实真的有辅助工具(有挂细节)-哔哩哔哩1、每一步都需要思考,不同水...
第8分钟了解!锄大地小程序辅助... 第8分钟了解!锄大地小程序辅助器!原来一直总是有辅助软件(有挂教学)-哔哩哔哩1、锄大地小程序辅助器...
第1分钟了解!中至鹰潭亲友圈辅... 第1分钟了解!中至鹰潭亲友圈辅助!切实真的有辅助app(有挂总结)-哔哩哔哩1、游戏颠覆性的策略玩法...
7分钟了解!潮汕透视辅助!好像... 7分钟了解!潮汕透视辅助!好像真的是有辅助方法(有挂秘籍)-哔哩哔哩1、每一步都需要思考,不同水平的...
第二分钟了解!新道游房卡辅助器... 第二分钟了解!新道游房卡辅助器!原来是有辅助工具(发现有挂)-哔哩哔哩一、新道游房卡辅助器游戏安装教...
第9分钟了解!心悦游戏透视辅助... 第9分钟了解!心悦游戏透视辅助器!好像是有辅助脚本(有挂功能)-哔哩哔哩该软件可以轻松地帮助玩家将心...
第6分钟了解!宝宝游戏辅助器!... 第6分钟了解!宝宝游戏辅助器!确实真的是有辅助教程(有挂技巧)-哔哩哔哩1、该软件可以轻松地帮助玩家...
第八分钟了解!兴动助手辅助!好... 第八分钟了解!兴动助手辅助!好像是真的有辅助脚本(有挂细节)-哔哩哔哩1、兴动助手辅助有没有辅助教程...